Retrieving data from view, should I use model binder?

ⅰ亾dé卋堺 提交于 2019-12-04 12:37:52

Everything is perfect until step 3 where you mention foreach loops in a view. That's where I would stop and use editor templates instead. So replace the loop in your view by:

<%= Html.EditorForModel() %>

and inside the corresponding editor template which will be rendered for each element of the model collection (~/Views/Shared/EditorTemplates/CustomFields.ascx):

<div class="editor-label">
   <%= Html.LabelFor(x => x.Name) %>
</div>
<div class="editor-field">
   <%= Html.TextBoxFor(x => x.Name) %>
</div>
<div class="editor-field">
   <%= Html.TextBoxFor(x => x.Value) %>
</div>
<div class="editor-field">
   <%= Html.TextBoxFor(x => x.Description) %>
</div>
<div class="editor-field">
   <%= Html.TextBoxFor(x => x.FieldType) %>
</div>

then simply:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(IEnumerable<CustomFields> fields)
{
    //code here...
}

No need of any model binders. The editor template will take care of generating proper names for the input fields so that they are correctly bound.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!