Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net MVC, ViewPage<Dynamic> and EditorFor/LabelFor

I'm playing with MVC3 using the Razer syntax, though I believe the problem to be more general.

In the controller, I have something like:

ViewModel.User = New User(); // The model I want to display/edit
ViewModel.SomeOtherProperty = someOtherValue; // Hense why need dynamic
Return View();

My View inherits from System.Web.Mvc.ViewPage

But if I try to do something like:

<p>
@Html.LabelFor(x => x.User.Name
@Html.EditorFor(x => x.User.Name
</p>

I get the error: "An expression tree may not contain a dynamic operation"

However, the use of ViewPage seems quite common, as are EditorFor/LabelFor. Therefore I'd be surprised if there's not a way to do this - appreciate any pointers.

like image 546
Saqib Avatar asked Sep 16 '10 16:09

Saqib


People also ask

What is difference between EditorFor and Textboxfor in MVC?

it's absolutly wrong answer, becuase the key difference is that Texbox returns input and editorfor returns your template where input is default template for editorfor.

What is HTML EditorFor in MVC?

Create HTML Controls for Model Class Properties using EditorFor() ASP.NET MVC includes the method that generates HTML input elements based on the datatype. The Html. Editor() or Html. EditorFor() extension methods generate HTML elements based on the data type of the model object's property.

How does HTML LabelFor work?

HTML label: Main TipsHTML label acts as a caption for a specified element. It is very convenient to use HTML label for <input> elements. It increases the clickable area, as clicking the label activates the input as well.


1 Answers

Don't use ViewPage<Dynamic>. I would recommend you using a view model and strongly type your view to this view model:

var model = new MyViewModel
{
    User = new User
    {
        Name = "foo"
    },
    SomeOtherProperty = "bar"
};
return View(model);

and then strongly type your view to ViewPage<MyViewModel> and:

@Html.LabelFor(x => x.User.Name)
@Html.EditorFor(x => x.User.Name)
<div>@Model.SomeOtherProperty</div>
like image 170
Darin Dimitrov Avatar answered Oct 20 '22 13:10

Darin Dimitrov