Csharp/C#教程:如何在HtmlHelper中调用`EditorExtensions.EditorFor`?分享


如何在HtmlHelper中调用`EditorExtensions.EditorFor`?

我在CreateView中使用不同的模型,所有模型都inheritance自BaseModel。 调用正确的EditorFor我创建了一个获取Model和实际属性的HtmlHelper。 但我不知道如何调用它。

BaseModel:

public abstract class BaseModel { protected IEnumerable PropertyInfoCache { get; set; } protected IEnumerable EnumeratedPropertyCache { get; set; } protected BaseModel() { PropertyInfoCache = this.GetType().GetProperties(); EnumeratedPropertyCache = PropertyInfoCache.Select(p=> new EnumeratedProperty(p.Name,p.GetType())); } public IEnumerable EnumerateProperties() { return EnumeratedPropertyCache; } public object GetPropertyValue(string PropertyName) { var property = PropertyInfoCache.SingleOrDefault(i=>i.Name==PropertyName); if(property!=null) return property.GetValue(this,null); return null; } } public class EnumeratedProperty { public string Name { get; private set; } public Type Type { get; private set; } public EnumeratedProperty(string PropertyName, Type PropertyType) { this.Name = PropertyName; this.Type = PropertyType; } } 

在我看来:

 @foreach (var property in Model.EnumerateProperties()) { @Html.EditorForProperty(Model,property); } 

的HtmlHelper:

 public static class ExtensionMethods { public static MvcHtmlString EditorForProperty(this HtmlHelper html, BaseModel Model, EnumeratedProperty property) { // creates an error: The type arguments for method 'EditorFor' cannot be inferred from the usage. Try specifying the type arguments explicitly. return System.Web.Mvc.Html.EditorExtensions.EditorFor(html, Model => Model.GetPropertyValue(property.Name) ); } } 

EditorFor识别对象的类型,所以你想要做的是从EnumeratedProperty类中的值中提取类型,而不是直接传递类,并从中传递值。

上述就是C#学习教程:如何在HtmlHelper中调用`EditorExtensions.EditorFor`?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1008484.html

(0)
上一篇 2021年12月29日
下一篇 2021年12月29日

精彩推荐