MVC 3 with forms and lists: the default binder and editor

Model:

public class MyObject
{
    public IList<Entry> Entries;
}

public class Entry
{
    public string Name { get; set; }
}

If I use default Editor (model => model.Entries), the values ​​of the / id name are:

<input type="text" value="" name="Entries[0].Name" id="Entries_0__Name">

If instead I want to create an EditorFor template, for example:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<List<CMS.Models.MyObject>>" %>

<div class="list">
<%
    for (int i = 0; i < Model.Count; i++)
    { %>
    <div class="object" id="<%: i %>">
        <%: Html.EditorFor(model => Model[i]) %>
        <%: Html.ValidationMessageFor(model => Model[i]) %>
    </div>
<%  } %>
</div>

The emitted name / identifier values ​​are:

<input type="text" value="" name="Entries.[0].Name" id="Entries__0__Name">

Thus, the name has a period between the property name and [0], and the identifier has an additional underscore to the left of the index number. This does not work with default model binding. Is there a way to do this that works with model binding by default?

+3
source share
1 answer

I think you can do most of this using templates without having to explicitly iterate over the list, which seems to cause problems with model binding.

:

MyObject

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<CMS.Models.MyObject>" %>

<div class="list">
    <%: Html.EditorFor(m => m.Entries) %>
</div>

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<CMS.Models.Entry>" %>

<div class="object" id="<%: ??? %>">
    <%: Html.EditorFor(m => m.Name) %>
    <%: Html.ValidationMessageFor(m => m.Name) %>
</div>

, , , id div, , . , , .

+3

Source: https://habr.com/ru/post/1791371/


All Articles