7

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.

3 Answers 3

4

Absolutely, the assignment is fine.

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

3 Comments

There are no static classes involved.
no it isn't. It's a property on the controller which is an IPrincipal which has only a getter. This getter calls the HttpContext.User property which can be mocked. It is not static.
@darin-dimitrov Not sure what you meant about static classes being involved? Thanks for the responses though.
2

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.

Comments

1

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.

1 Comment

Thanks. Which bit would go into the global model class -- the User.Identity.Name?

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.