将绑定一个IEnumerable℃的扩展的HtmlHelper方

将绑定一个IEnumerable℃的扩展的HtmlHelper方

本文介绍了如何创建将绑定一个IEnumerable℃的扩展的HtmlHelper方法; T>到一个表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的视图模型:

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;}
}

在我看来,我做了这样的事情:

In my view I have done something like this:

<table>
 @foreach(var item in Model.Executors)
   {
      <tr>
         <td>item.ExecutorID</td>
         <td>@string.Format("{0} {1}",item.FirstName,item.LastName)</td>
      </tr>
   }
</table>

现在,加载视图时,不会有任何问题,但我可能需要编辑表,我想更改提交表单的时候坚持。我能想到的唯一的办法是将正确绑定一个IEnumerable到表中的HtmlHelper扩展方法,但我不知道该怎么做。我很乐意看到一些code。或者有没有其他的方式来实现这一目标?

Now, when loading the view, there won't be any problem, but I might need to edit the table and I want the changes to persist when submitting the form. The only way I can think of is an HtmlHelper extension method that will properly bind an IEnumerable to a table but I have no idea how to do that. I'd be happy to see some code. Or is there any other way to achieve this?

推荐答案

办法之一如下:

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)

请注意,你需要做一个执行者列表与LT; TaskExecutor的方式&gt; 为索引的正常工作

Please note you would need to make the Executors a List<TaskExecutor> for the indexing to work properly.

循环,并将其命名变量的索引将保持模型绑定开心。你可以添加更多的领域,我在上面已经评论说。

The indexing of the loop and and name variable would keep the model binding happy. You could add further fields where I have commented above.

您也可以使用 Html.TextBox Html.TextBoxFor 如果需要产生的输入。

You could also use Html.TextBox or Html.TextBoxFor to generate the inputs if needed.

这篇关于如何创建将绑定一个IEnumerable℃的扩展的HtmlHelper方法; T&GT;到一个表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 02:31