MVC binding to model with list property ignores other properties

后端 未结 3 895
别跟我提以往
别跟我提以往 2020-12-08 07:20

I have a basic ViewModel with a property that is a List of complex types. When binding, I seem to be stuck with getting either the list of values, OR the other model propert

3条回答
  •  情话喂你
    2020-12-08 07:39

    Alternatively you could have created an EditorTemplate for your nested ViewModel as follows.

    @model MyDataItem
    @Html.HiddenFor(model => model.Id)
    @Html.HiddenFor(model => model.ParentId)
    @Html.HiddenFor(model => model.Name)
    @Html.TextBoxFor(model => model.Value)
    

    Create a folder named 'EditorTemplates' in your 'Shared' folder and save the above as 'MyDataItem.cshtml'.

    Then in your View, just call the following instead of the foreach loop:

    @Html.EditorFor(model => model.Data)
    

    Feels a bit less hackier IMO :)

提交回复
热议问题