1

我有一个简单的 post 操作,它试图从 post 方法将新模型返回到视图。出于某种原因,当我返回新模型时,我总是看到我发布的模型,为什么会发生这种情况?我需要在发布操作中更改模型的值并将它们返回给用户,但由于某种原因我无法做到这一点?

public ActionResult Build()
{
    return View(new Person());
}

[HttpPost]
public ActionResult Build(Person model)
{
    return View(new Person() { FirstName = "THX", LastName = "1138" });
}

这是视图代码;

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

    <fieldset>
        <legend>Person</legend>

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

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

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

如果我打开表格并在名字中输入“John”,在姓氏中输入“Smith”并发布表格,我会从发布操作中得到“John”、“Smith”而不是“THX 1138”有没有办法覆盖此行为?我也想知道为什么会这样?

4

1 回答 1

5

您可以通过添加this.ViewData = null;到您的发布操作来指示 ASP.NET MVC 忘记发布的值来做到这一点:

[HttpPost]
public ActionResult Build(Person model)
{
    this.ViewData = null;

    return View(new Person() { FirstName = "THX", LastName = "1138" });
}
于 2013-06-20T12:50:00.820 回答