2

I'm creating user control in MVC3 application. 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.

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. Unfortunately nothing is being rendered.

Everything works fine when I use bool value or some not empty string. Here's an example:

var viewModel = new MyViewModel { Value = true };

Html.EditorFor renders checkbox input:

Value property of type bool

I did some research, but for now I didn't found solution.

2 Answers 2

1

Not a direct answer, but can't you just make your ViewModel generic:

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This is simplified example. In real app I have generic type - just like you said. But I need to be able to create list of MyViewModel. As you know I can't create list of generic types, so I created interface (IMyViewModel) with property Value of type object.
1

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. What is wrong with expression p => p.Value?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.