简体   繁体   English

如何通过属性名称呈现模型属性的编辑器模板

[英]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. 最终目标是为仅在运行时已知的模型属性呈现一个编辑器模板,该编辑器模板不会从ViewBag中获取其值。

Html.Editor will use the ViewBag value if the property names match. 如果属性名称匹配,则Html.Editor将使用ViewBag值。 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. 如果不是这样,则可以使用某种方式呈现编辑器模板,而不使用viewbag值而不是模型的值。 I'm totally fine with doing this, IF I CAN IGNORE THE VIEWBAG VALUES SOMEHOW: 如果我可以略过VIEWBAG的值,我完全可以这样做:

@Html.Editor(propName, other, arguments)

You'll probably have to use Html.Partial with a custom ViewDataDictionary. 您可能必须将Html.Partial与自定义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. 注意:我简化了此示例以说明核心概念,但是您可以根据需要将其扩展为读取UIHintAttribute等。

Note 2: You may also want to copy values from Html.ViewData to the new ViewDataDictionary to keep your modelstate etc. 注意2:您可能还想将值从Html.ViewData复制到新的ViewDataDictionary,以保持您的模型状态等。

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. 假设SomePropertyName是您模型的属性的名称,该属性在视图中具有强类型。

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. 我的解决方案是使用属性名称作为字符串的@ Html.Editor()方法,并使用在模型对象上不太可能找到的ViewBag键。

Not ideal, but should work well. 不理想,但应该能很好地工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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