How should I automatically populate Html.EditorFor with a value in ASP.Net MVC3?

I just look at ASP.Net MVC3 and in one of the automatically created views for Create, it uses "Html.EditorFor (model => model.User)" to provide a text box for the user to enter the username. Ideally, I would automatically populate this with @ User.Identity.Name.

What is the right way to achieve this? Does Html.EditorFor allow me to automatically populate it in the view, or should I install it on the controller when transferring it?

I found that if I change the Create method in the controller, then:

public ActionResult Create() { return View(); } 

For this:

  public ActionResult Create() { MyObject myobject = new MyObject(); myobject.User = User.Identity.Name; return View(myobject); } 

It seems to work. Is this the right way to do this?

Thanks in advance for any confirmation that I am doing this correctly.

+7
source share
3 answers

Absolutely, the destination is beautiful.

+4
source

This is absolutely the right way. You define a view model ( MyObject ) containing a custom string property, then create your controller action and populate this model and finally pass the view model to the view for display. It is also easy to unit test, because the User.Identity property on the controller is an abstraction that can be styled.

+2
source

this is a good way in this case, but if you create a large project, it is better to create a global model class where you put all your models, and not in the controller.

+1
source

All Articles