Text box default value in Razor syntax

依然范特西╮ 提交于 2019-12-25 02:35:07

问题


    <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:


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.



来源:https://stackoverflow.com/questions/6668018/text-box-default-value-in-razor-syntax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!