View Model IEnumerable<> property is coming back null (not binding) from post method?

后端 未结 2 654
予麋鹿
予麋鹿 2020-12-02 14:02

I have a view model that contains a Product class type and an IEnumerable< Product > type. On the post the first level product object comes back binded from the viewmode

2条回答
  •  执笔经年
    2020-12-02 14:21

    Travis's answer will address the issue. Here is another approach using EditorTemplates

    You can use an Editor template to display the Products and it will work fine.

    1) Create a Folder called "EditorTemplates" under your Views/Home folder

    2 ) Add a view called "Products" inside that. Add this code to that view

    @model SO_MVC.Models.Product
    @{
       Layout = null;
    }
    

    @Html.LabelFor(x=>x.ID) @Html.EditorFor(x=>x.ID)

    @Html.LabelFor(x=>x.Name) @Html.EditorFor(x=>x.Name)

    @Html.LabelFor(x=>x.Price) @Html.EditorFor(x=>x.Price)

    @Html.HiddenFor(x=>x.Id)

    and in your Main View, you can call this Editor template like this

      @Html.EditorFor(m=>m.Products)
    

提交回复
热议问题