简体   繁体   中英

How to render editor template for model property by property name

The end goal is to render an editor template, for a model property, known only at run time, that will not take it's value from the ViewBag.

Html.Editor will use the ViewBag value if the property names match. I don't want this and I hate this "feature".

I hope that this is possible somehow:

var propName = "MyProperty";
var expression = GiveMeTheExpression();
@Html.EditorFor(expression,"MyEditorTemplate")

If not this then some way of rendering an editor template without the viewbag values being used instead of the model's values. I'm totally fine with doing this, IF I CAN IGNORE THE VIEWBAG VALUES SOMEHOW:

@Html.Editor(propName, other, arguments)

You'll probably have to use Html.Partial with a custom ViewDataDictionary.

object knownAtRuntime = ViewBag.ObjectName; // Adapt to your solution
string templateName = String.Concat("EditorTemplates/", knownAtRuntime.GetType().Name);            

@Html.Partial(templateName, knownAtRuntime, new ViewDataDictionary(knownAtRuntime));

Note: I made this example simple to illustrate the core concept but you can of course extend it to read UIHintAttribute etc if you like.

Note 2: You may also want to copy values from Html.ViewData to the new ViewDataDictionary to keep your modelstate etc.

Why not try this ?

@Html.EditorFor(x=>x.SomePropertyName)

Assuming SomePropertyName is the name of a Property of your Model which is strongly typed to your view.

Shyju正在处理强类型对象,如果我对您的理解正确,则需要类似以下内容: asp.net mvc 3和动态视图生成

My solution was to use the @Html.Editor() method with property name as string and to use ViewBag keys that are very unlikely to be found on the model object.

Not ideal, but should work well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM