输入名称不正确MVC EditorTemplate For Array

时间:2012-12-18 05:40:27

标签: asp.net-mvc

我的代码是

public class TarkibVM:BaseVM
{
    public int TarkibID { get;set;}

    [UIHint("KhorakTarkibList")]
    public KhorakTarkibVM[] KhorakTarkibVms { get; set; }}


public class KhorakTarkibVM
{
    public int KhorakID{ get;set;}

    public string Name{ get;set;}
}

KhorakTarkibList.cshtml:

@model MvcMarkazToyoor.Models.KhorakTarkibVM[]

<table>

@for (int index = 0; index < Model.Count(); index++)
{
    <tr>
        @Html.EditorFor(modelItem => modelItem[index])
    </tr>
}
</table>

KhorakTarkibVM.cshtml:

@model MvcMarkazToyoor.Models.KhorakTarkibVM

<td>
    @Html.EditorFor(modelItem => modelItem.Checked)
</td>
<td>
    @Html.DisplayFor(modelItem => modelItem.KhorakID)
    @Html.HiddenFor(modelItem => modelItem.KhorakID)
</td>
<td>
    @Html.DisplayFor(modelItem => modelItem.Name)
</td>

Create.cshtml:

@model MvcMarkazToyoor.Models.TarkibVM

@using (Html.BeginForm()) {
@Html.ValidationSummary(true)

    <div class="editor-label">
        @Html.LabelFor(model => model.GroupID)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.TarkibID)
        @Html.ValidationMessageFor(model => model.TarkibID)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.KhorakTarkibVms)
    </div>

    <p>
        <input type="submit" value="Create" />
    </p>}

在这段代码中,所有东西都没问题,除了数组输入的名称没有正确 我希望name =“KhorakTarkibVms [0] .Percent” 但生成的名称是name =“KhorakTarkibVms。[0] .Percent”

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

1 - 在这种情况下你不能使用Array,而是使用List<>

2 - 不需要迭代KhorakTarkibVms所以不需要KhorakTarkibList.cshtml

所以这是新的TarkibVM类:

public int TarkibID { get; set; }
public int GroupID { get; set; }
public List<KhorakTarkibVM> KhorakTarkibVms { get; set; }

不记得删除KhorakTarkibList.cshtml或重命名或删除UIhintAttribute

不要迭代KhorakTarkibVms,所以新的Create.cshtml是:

@model MvcMarkazToyoor.Models.TarkibVM

@using (Html.BeginForm()) {
@Html.ValidationSummary(true)

    <div class="editor-label">
        @Html.LabelFor(model => model.GroupID)
    </div>
    <div class="editor-field">
       @Html.EditorFor(model => model.TarkibID)
       @Html.ValidationMessageFor(model => model.TarkibID)
    </div>
    <div class="editor-field">
       <table>
           @Html.EditorFor(model => model.KhorakTarkibVms)
       </table>
    </div>

    <p>
        <input type="submit" value="Create" />
    </p>
}

在新KhorakTarkibVM.cshtml中添加tr标记:

<tr>
    <td>
        @Html.EditorFor(modelItem => modelItem.Checked)
    </td>
    <td>
        @Html.DisplayFor(modelItem => modelItem.KhorakID)
        @Html.HiddenFor(modelItem => modelItem.KhorakID)
    </td>
    <td>
        @Html.DisplayFor(modelItem => modelItem.Name)
    </td>
</tr>