asp.net-mvc – EditorTemplates / Object.cshtml使用EditorFor()而不是Editor()?

我正在尝试创建一个复制 Html.EditorForModel()的通用编辑器模板,以便以后自定义和构建. Brad Wilson’s template变得非常接近,但我发现当ViewData(或ViewBag)和模型中存在相同的密钥时,它会窒息.例如,如果视图模型也具有Title属性,则ViewBag.Title会导致问题.

我学习了here,使用强类型助手(即Html.EditorFor(x => x.Title)而不是Html.Editor(“Title”)似乎有所帮助.所以我试图修改Brad的模板,但我遇到了砖墙,因为到目前为止我没有尝试过任何工作.我无法弄清楚如何在我不知道模型类型的上下文中使用强类型帮助器,例如编辑器模板.

有没有办法像Brad那样创建一个Object模板,但是使用强类型的助手(即LabelFor,EditorFor,ValidatorMessageFor)而不是弱类型的助手(即Label,Editor,ValidatorMessage)?

谢谢.

解决方法

我通过稍微迂回的方式解决了这个问题,方法是在调用@Html.Editor之前删除ViewData,然后再将其放回去.

Object.cshtml:

object oldViewData = null;
        var hasConflictingViewData = ViewData.TryGetValue(prop.PropertyName,out oldViewData);

        if (hasConflictingViewData)
        {
            ViewData.Remove(prop.PropertyName);
        }

        @Html.Editor(prop.PropertyName)

        if (hasConflictingViewData)
        {
            ViewData.Add(prop.PropertyName,oldViewData);
        }

我能想到的唯一另一个选择是使用大量的反射来通常使用运行时类型调用EditorFor,并传入相关属性的表达式.

相关文章

判断URL文件是不是在于在。private static bool UrlIsExist(...
由于在.net中,Request时出现有HTML或Javascript等字符串时,...
public static bool ProcessIdCard(this string idCard, out...
protected void Page_Load(object sender, EventArgs e){ Sc...