这是我的 View 模型:
public class TaskViewModel{
public int TaskID{get;set;}
public IEnumerable<TaskExecutor> Executors{get;set;}
}
public class TaskExecutor{
public int ExecutorID{get;set;}
public string LastName{get;set;}
public string FirstName{get;set;}
}
在我看来,我做了这样的事情:
<table>
@foreach(var item in Model.Executors)
{
<tr>
<td>item.ExecutorID</td>
<td>@string.Format("{0} {1}",item.FirstName,item.LastName)</td>
</tr>
}
</table>
现在,加载 View 时不会有任何问题,但我可能需要编辑表格,并且我希望在提交表单时保留更改。我能想到的唯一方法是 HtmlHelper 扩展方法,它将正确地将 IEnumerable 绑定(bind)到表,但我不知道如何做到这一点。我很高兴看到一些代码。或者还有其他方法可以实现这一点吗?
最佳答案
一个选项可能如下:
namespace System.Web.Mvc
{
public static class ExecutorsExtensions
{
public static MvcHtmlString Executors(this HtmlHelper helper, List<TaskExecutor> executors)
{
var sb = new StringBuilder();
sb.Append("<table>");
for (var i = 0; i < executors.Count; i++)
{
sb.Append("<tr>");
sb.Append(string.Format("<td><input name=\"Executors[{0}].FirstName\" value=\"{1}\"></td>", i, executors[i].FirstName));
// add other cells here
sb.Append("<tr>");
}
sb.Append("</table>");
return new MvcHtmlString(sb.ToString());
}
}
}
使用
@Html.Executors(Model.Executors)
请注意,您需要将执行者设为 List<TaskExecutor>
使索引正常工作。
循环和名称变量的索引将使模型绑定(bind)保持良好。您可以在我上面评论过的地方添加更多字段。
您还可以使用Html.TextBox
或Html.TextBoxFor
如果需要生成输入。
关于asp.net-mvc - 如何创建将 IEnumerable<T> 绑定(bind)到表的 HtmlHelper 扩展方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28237650/