如何创建将 IEnumerable<T> 绑定到 table 的 HtmlHelper 扩展方法

How to create an HtmlHelper extension method that will bind an IEnumerable<T> to a table

这是我的视图模型:

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>

现在,加载视图时不会有任何问题,但我可能需要编辑 table 并且我希望在提交表单时保留更改。我能想到的唯一方法是将 IEnumerable 正确绑定到 table 的 HtmlHelper 扩展方法,但我不知道该怎么做。我很乐意看到一些代码。或者还有其他方法可以实现吗?

一个选项如下:

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> 才能使索引正常工作。

循环和名称变量的索引将使模型绑定愉快。您可以在我上面评论的地方添加更多字段。

如果需要,您也可以使用 Html.TextBoxHtml.TextBoxFor 生成输入。