asp.net-mvc - 如何创建将 IEnumerable<T> 绑定(bind)到表的 HtmlHelper 扩展方法

标签 asp.net-mvc html-table ienumerable model-binding

这是我的 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.TextBoxHtml.TextBoxFor如果需要生成输入。

关于asp.net-mvc - 如何创建将 IEnumerable<T> 绑定(bind)到表的 HtmlHelper 扩展方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28237650/

相关文章:

javascript - 下拉菜单无缝地路由到不同的 Controller /操作方法

asp.net-mvc - Azure VM NGINX Plus + Web 应用程序导致 404

asp.net-mvc - 测试使用DbContext的存储库的最佳方法

PHP/MySql HTML 表分组

html - css/html ul 表格行元素水平分布

c# - 如何将两个 IEnumerable<T> 连接成一个新的 IEnumerable<T>?

c# - 迭代 IEnumerable,特殊套管最后一个元素

html - 为什么我的页脚不在页面底部?

html - 为什么忽略列宽?

c# - 我可以将 C# 函数标记为 "this function does not enumerate the IEnumerable parameter"吗?