0

基本上我有一个创建视图,人们可以在其中创建如下所示的数据库条目:

@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Trade</legend>

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

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

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

该数据库还有一个名为“名称”的字段,我想包含创建该条目的用户的名称。我可以使用@User.Identity.Name 获取当前用户的用户名,但我不知道如何做到这一点,因此当用户单击“提交”时,它会自动添加到名称字段中。

提前感谢您的帮助!

4

1 回答 1

2

您无需将其填写到名称字段中。在处理帖子的控制器中,只需使用:

[HttpPost] 
public ActionResult Create(Trade trade) { 
trade.Name=HttpContext.User.Identity.Name; //this is where the current user is added
if (ModelState.IsValid) { 
db.Movies.Add(trade); 
db.SaveChanges(); 
return RedirectToAction("Index"); 
} 
return View(trade); 
} 
于 2013-06-23T18:18:06.960 回答