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.
Absolutely, the assignment is fine.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With