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

对着背影说爱祢 提交于 2019-12-12 18:26:36

问题


This is my view model:

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>

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?


回答1:


One option could be as follows:

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());

        }
    }
}

Usage

@Html.Executors(Model.Executors)

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.

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



来源:https://stackoverflow.com/questions/28237650/how-to-create-an-htmlhelper-extension-method-that-will-bind-an-ienumerablet-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!