ZVenue
ZVenue

Reputation: 5027

Text box default value in Razor syntax

    <div class="editor-label">
        @Html.LabelFor(model => model.UserName)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.AccountModel.UserName)
        @Html.ValidationMessageFor(model => model.AccountModel.UserName)
    </div>

On this page load (View load), I would like the Username text box to have its value automatically populated from the standard aspnet membership informtion. How can assign this default value to the text box. Please help. thank you

Upvotes: 1

Views: 6273

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039498

In your controller action you could populate the view model and set the corresponding properties on it. So assuming your view is strongly typed to MyViewModel:

[Authorize]
public ActionResult Foo()
{
    var model = new MyViewModel
    {
        UserName = User.Identity.Name
    };
    return View(model);
}

and in the view simply:

<div class="editor-label">
    @Html.LabelFor(model => model.UserName)
</div>
<div class="editor-field">
    @Html.EditorFor(model => model.UserName)
    @Html.ValidationMessageFor(model => model.UserName)
</div>

If your view model has some AccountModel property, you will have to instantiate and populate it in the controller action. In my example I have flattened the view model.

Upvotes: 5

Related Questions