Text box default value in Razor syntax

2019-08-23 04:44发布

    <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

1条回答
放荡不羁爱自由
2楼-- · 2019-08-23 04:52

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.

查看更多
登录 后发表回答