Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I auto-fill the Html.EditorFor with a value in ASP.Net MVC3?

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

What is the correct way to achieve this? Does Html.EditorFor allow me to automatically populate it in the view, or should I be setting that at the controller when passing it in?

I've found that if I change the Create method in the controller from this:

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

To this:

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

This seems to work. Is this the correct way to do this?

Thanks in advance for any confirmation that I'm doing this right.

like image 296
Darren Avatar asked May 04 '11 13:05

Darren


3 Answers

Absolutely, the assignment is fine.

like image 138
Daniel A. White Avatar answered Oct 19 '22 06:10

Daniel A. White


This is absolutely the correct way. You define a view model (MyObject) containing the User string property, then have your controller action instantiate and populate this model and finally pass the view model to the view for displaying. It is also easy to unit test because the User.Identity property on the controller is an abstraction that could be mocked.

like image 44
Darin Dimitrov Avatar answered Oct 19 '22 06:10

Darin Dimitrov


its a good way in this case, but if you bild a big project it's better to create a global model class where you will put all your models, not in controller.

like image 1
Evgeniy Labunskiy Avatar answered Oct 19 '22 08:10

Evgeniy Labunskiy