[英]ASP.NET MVC3 Html.EditorFor and property of type object
I'm creating user control in MVC3 application.我正在 MVC3 应用程序中创建用户控件。 My view model looks like that:我的视图模型如下所示:
public class MyViewModel
{
public object Value { get; set; }
}
The Value property could be an int, string or bool so I can't use [DataType]
attribute. Value 属性可以是 int、string 或 bool,所以我不能使用[DataType]
属性。
When I create my view model:当我创建我的视图模型时:
var viewModel = new MyViewModel { Value = "" };
or或者
var viewModel = new MyViewModel { Value = 1 };
I assume that this code:我假设这段代码:
<%: Html.EditorFor(p => p.Value) %>
should render an HTML input of type textbox.应该呈现文本框类型的 HTML 输入。 Unfortunately nothing is being rendered.不幸的是,没有任何东西被渲染。
Everything works fine when I use bool value or some not empty string.当我使用 bool 值或一些非空字符串时,一切正常。 Here's an example:下面是一个例子:
var viewModel = new MyViewModel { Value = true };
Html.EditorFor
renders checkbox input: Html.EditorFor
呈现复选框输入:
I did some research, but for now I didn't found solution.我做了一些研究,但现在我没有找到解决方案。
Not a direct answer, but can't you just make your ViewModel generic:不是直接的答案,但你不能让你的 ViewModel 通用:
public class MyViewModel<T>
{
public T Value { get; set; }
}
This way, the Html helper method can resolve at compile time exactly what type value is, and exactly which editor to render.这样,Html helper 方法就可以在编译时准确地解析出什么类型的值,以及要呈现的编辑器。
I used:我用了:
<%: Html.Editor("Value") %>
instead of:代替:
<%: Html.EditorFor(p => p.Value) %>
and everything works great!一切都很好! The textbox is being rendered for empty string or int value.正在为空字符串或 int 值呈现文本框。 What is wrong with expression p => p.Value
?表达式p => p.Value
什么问题?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.