问题
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