gpt4 book ai didi

c# - EditorFor IEnumerable 与 TemplateName

转载 作者:IT王子 更新时间:2023-10-29 04:38:23 25 4
gpt4 key购买 nike

假设我有一个简单的模型来解释用途:

public class Category
{
...
public IEnumerable<Product> Products { get; set; }
}

查看:

@model Category
...
<ul>
@Html.EditorFor(m => m.Products)
</ul>

编辑器模板:

@model Product
...
<li>
@Html.EditorFor(m => m.Name)
</li>

请注意,我不必为 IEnumerable<Product> 定义 EditorTemplate , 我只能为 Product 创建它模型和 MVC 框架足够聪明,可以使用自己的 IEnumerable 模板。它遍历我的集合并调用我的 EditorTemplate。

输出的 html 会是这样的

...
<li>
<input id="Products_i_Name" name="Products[i].Name" type="text" value="SomeName">
</li>

毕竟我可以将其发布到我的 Controller 。

但是,当我使用模板名称定义 EditorTemplate 时,为什么 MVC 不执行此操作?

@Html.EditorFor(m => m.Products, "ProductTemplate")

在这种情况下,我必须将属性的类型更改为 IList<Product> ,自己遍历集合调用EditorTemplate

@for (int i = 0; i < Model.Products.Count; i++)
{
@Html.EditorFor(m => m.Products[i], "ProductTemplate")
}

这对我来说似乎是一种肮脏的解决方法。是否有其他更清洁的解决方案来执行此操作?

最佳答案

好了,现在我只欠Darin 9999啤酒

    public static MvcHtmlString EditorForMany<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, IEnumerable<TValue>>> expression, string templateName = null) where TModel : class
{
StringBuilder sb = new StringBuilder();

// Get the items from ViewData
var items = expression.Compile()(html.ViewData.Model);
var fieldName = ExpressionHelper.GetExpressionText(expression);
var htmlFieldPrefix = html.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix;
var fullHtmlFieldPrefix = String.IsNullOrEmpty(htmlFieldPrefix) ? fieldName : String.Format("{0}.{1}", htmlFieldPrefix, fieldName);
int index = 0;

foreach (TValue item in items)
{
// Much gratitude to Matt Hidinger for getting the singleItemExpression.
// Current html.DisplayFor() throws exception if the expression is anything that isn't a "MemberAccessExpression"
// So we have to trick it and place the item into a dummy wrapper and access the item through a Property
var dummy = new { Item = item };

// Get the actual item by accessing the "Item" property from our dummy class
var memberExpression = Expression.MakeMemberAccess(Expression.Constant(dummy), dummy.GetType().GetProperty("Item"));

// Create a lambda expression passing the MemberExpression to access the "Item" property and the expression params
var singleItemExpression = Expression.Lambda<Func<TModel, TValue>>(memberExpression,
expression.Parameters);

// Now when the form collection is submitted, the default model binder will be able to bind it exactly as it was.
var itemFieldName = String.Format("{0}[{1}]", fullHtmlFieldPrefix, index++);
string singleItemHtml = html.EditorFor(singleItemExpression, templateName, itemFieldName).ToString();
sb.AppendFormat(singleItemHtml);
}

return new MvcHtmlString(sb.ToString());
}

关于c# - EditorFor IEnumerable<T> 与 TemplateName,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14038392/

25 4 0