我在这个问题上停留了一段时间..
我创建了一个简单的 View 模型:
public class AddTranslationViewModel
{
public List<ProjectTranslation> ProjectTranslations { get; set; }
public AddTranslationViewModel()
{
ProjectTranslations = new List<ProjectTranslation>();
}
}
ProjectTranslation 类:
public class ProjectTranslation
{
public int ProjectTranslationId { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Address { get; set; }
public int LanguageId { get; set; }
public Language Language { get; set; }
public int ProjectId { get; set; }
public Project Project { get; set; }
}
使用 AddTranslationViewModel 的简单 View
<table class="table">
@foreach (var item in Model.ProjectTranslations)
{
@Html.HiddenFor(modelItem => item.ProjectTranslationId)
<tr>
<td>
@Html.DisplayFor(modelItem => item.Language.LanguageCode)
</td>
<td>
@Html.EditorFor(modelItem => item.Title)
</td>
</tr>
}
</table>
<input type="submit" value="Send" />
最后是我的 POST 方法:
public ViewResult AddTranslation(AddTranslationViewModel projectTranslations)
{
if (ModelState.IsValid)
{
//...
}
return View(projectTranslations);
}
这个想法非常基础,我想显示一个项目列表,应该可以在其中更改/编辑值。
但是,模型绑定(bind)不起作用,HTTPPost-Method AddTranslation 中的 projectsTranslations 参数始终为空。
这里有什么错误?
最佳答案
绑定(bind)到对象列表需要创建名称包含索引的输入字段结构,即:
<input type="text" name="YourArrayOrList[0].SomeProperty" value="123" />
<input type="text" name="YourArrayOrList[0].SomeOtherProperty" value="321" />
<input type="text" name="YourArrayOrList[1].SomeProperty" value="123" />
<input type="text" name="YourArrayOrList[1].SomeOtherProperty" value="321" />
此外,您需要使用 Razor 的 Html.BeginFrom
方法 ( see documentation ) 将表单指向 Controller 中正确的操作方法。
在你的情况下,它应该是这样的:
@using(Html.BeginForm("AddTranslation","YourControllerName"))
{
for (int i=0;i<Model.ProjectTranslations.Count; i++)
{
@Html.HiddenFor(model => model.ProjectTranslations[i].ProjectTranslationId)
<tr>
<td>
@Html.DisplayFor(model => model.ProjectTranslations[i].Language.LanguageCode)
</td>
<td>
@Html.EditorFor(model => model.ProjectTranslations[i].Title)
</td>
</tr>
}
}
如果您的方法不是编辑方法,而是 CREATE 方法,那么显然您的模型中的列表将有 0 个元素。在这种情况下,将 for 循环中的停止条件更改为所需的计数。
请记住,这个话题之前已经讨论过很多次了:
关于c# - ASP.NET MVC 5 模型绑定(bind)列表为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37238179/