Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 指定Html.EDITOR的模板名称,用于获取列表_C#_Asp.net Mvc_Razor - Fatal编程技术网

C# 指定Html.EDITOR的模板名称,用于获取列表

C# 指定Html.EDITOR的模板名称,用于获取列表,c#,asp.net-mvc,razor,C#,Asp.net Mvc,Razor,我的PersonModel对象有多个编辑器模板: Views/Person/EditorTemplates/PersonModel.cshtml Views/Person/EditorTemplates/RestrictedPersonModel.cshtml Views/Person/EditorTemplates/NoImagePersonModel.cshtml 作为测试,这些编辑器模板是相同的: @model MyApp.Models.PersonModel @Html.TextB

我的
PersonModel
对象有多个编辑器模板:

  • Views/Person/EditorTemplates/PersonModel.cshtml
  • Views/Person/EditorTemplates/RestrictedPersonModel.cshtml
  • Views/Person/EditorTemplates/NoImagePersonModel.cshtml
作为测试,这些编辑器模板是相同的:

@model MyApp.Models.PersonModel

@Html.TextBoxFor(model => model.Name)
使用以下视图时:

@model List<MyApp.Models.PersonModel>

@{
    ViewBag.Title = "Basket";
}

<h1>All People</h1>

@if (Model.Count() > 0)
{
    <div>
       This is a list of all the people:
    </div>

    using (Html.BeginForm("SendID", "Person", FormMethod.Post))
    {
        <div>

            @Html.EditorFor(model => model)

        </div>

        <div class="col-md-12">
            <button type="submit">
               Email IDs
            </button>
        </div>
    }
}
else
{
    <div>
        There are no people.
    </div>
}
我收到以下错误:

The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[MyApp.Models.PersonModel]', but this dictionary requires a model item of type 'PrintRoom.Models.PersonModel'.
更换时

@Html.EditorFor(model => model, "RestrictedPersonModel")

然后,
列表
不会传递到我的控制器中


如何指定要使用的编辑器模板,并且仍然在控制器中接收数据?

您需要使用
for
循环,而不是
foreach
循环

for(int i = 0; i < Model.Count; i++)
{
   @Html.EditorFor(m => m[i], "RestrictedPersonModel")
}
for(int i=0;im[i],“RestrictedPersonModel”)
}

foreach
生成重复的
name
属性,这些属性与您的模型没有关系(以及重复的
id
属性,这些属性是无效的html)

这实际上是可行的,但会导致另一个问题-此集合不会在发布表单时发送。“你知道怎么解决吗?”罗曼博罗维茨。是的,会的。如果它对您不起作用,那么它是由于代码的其他问题造成的。你需要问一个显示相关代码的新问题。我知道这是一个古老的问题,但我自己也遇到过同样的问题,对我来说这似乎是一个bug。如果为编辑器模板指定模板名称改变了它的工作方式并需要额外的代码,从而降低了使用编辑器模板的好处,那么提供允许为编辑器模板指定模板名称的重载有什么意义?
@foreach (PersonModel p in Model)
{
    @Html.EditorFor(model => p, "RestrictedPersonModel")
}
for(int i = 0; i < Model.Count; i++)
{
   @Html.EditorFor(m => m[i], "RestrictedPersonModel")
}