Search code examples
c#html.netmodel-view-controllerhtml-helper

Add model into model using Html helper HiddenFor C# MVC


I have a model like

public class Model
{
    public int Value { get; set; }
    public List<OtherModel> List { get; set; }
}

public class OtherModel
{
    public int Value1 { get; set; }
    public int Value2 { get; set; }
    public bool IsPropTrue { get; set; }
}

I am using Model in a View where I'm looping through the List to show data in a table.

Depending on whether one of the properties (IsPropTrue) in OtherModel is true or false, I want to use the HiddenFor Html helper and send the data to the HttpPost controller.

@model Model                                       
@foreach (var item in Model.List)
{                                          
    if (item.IsPropTrue)
    {
        @Html.HiddenFor(model=> item.Value1)
        @Html.HiddenFor(model=> item.Value2) 
    } 
}                          

I think it doesn't work because I should in some way add these properties to the OtherModel, which is inside the Model; But the way I have it now, I am adding properties to Model.


Solution

  • you can do it like this :

    @model Model                                       
    @foreach (var item in Model.List)
    {                                          
        if (item.IsPropTrue)
        {
            @Html.HiddenFor(model => model.List[Model.List.IndexOf(item)].Value1)
            @Html.HiddenFor(model => model.List[Model.List.IndexOf(item)].Value2)
        } 
    } 
    

    this way the binding system will bind the hidden fields with your List OtherModel in the Model