简体   繁体   English

ASP.NET MVC3 Html.EditorFor 和类型对象的属性

[英]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呈现复选框输入:

类型 bool 的值属性

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.

相关问题 ASP.NET MVC3 Html.EditorFor()问题 - ASP.NET MVC3 Html.EditorFor() problem ASP.NET MVC 2 - Html.Editor对于可以为空的类型? - ASP.NET MVC 2 - Html.EditorFor a nullable type? 在ASP.Net MVC3中为特定数据类型模板Html.EditorFor吗? - Templating Html.EditorFor for specific datatype in ASP.Net MVC3? ASP.NET MVC 2 中意外的 Html.EditorFor 行为 - Unexpected Html.EditorFor behavior in ASP.NET MVC 2 如何使 html.editor 在 asp.net mvc 2 中不可见? - how to make html.editorfor unvisible in asp.net mvc 2? ASP.NET MVC @ Html.EditorFor(模型=&gt;模型。属性)但是 - ASP.NET MVC @Html.EditorFor(model => model.property) But 是否可以从 ASP.NET MVC 中的 @Html.EditorFor 中删除或隐藏最后一个条目的建议 - Is it possible to remove or hide suggestions of last entries from @Html.EditorFor in ASP.NET MVC 如何在ASP.net MVC 5中使用@ Html.EditorFor自动填充表单中的字段? - How to auto fill fields in a form using @Html.EditorFor in ASP.net MVC 5? ASP.NET MVC 2:如何将Html.EditorFor用于自定义模型? - ASP.NET MVC 2: How do you use Html.EditorFor for custom models? 不使用Html.EditorFor()asp.net mvc创建模型的引用时出现的问题 - Issue when creating a reference of a Model without using Html.EditorFor() asp.net mvc
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM