3

很简单的情况,这是我的模型:

public class Comment
{
    [Required]
    public string Name { get; set; }
    [Required]
    public string Text { get; set; }

}

这是我的控制器:

public class CommentController : Controller
{
    //
    // GET: /Comment/Create

    public ActionResult Create()
    {
        return View();
    } 

    //
    // POST: /Comment/Create

    [HttpPost]
    public ActionResult Create(FormCollection collection)
    {
        Comment new_comment = new Comment();

        if (TryUpdateModel(new_comment))
        {
            return View(new Comment()); //problem is there
        }
        else
        {
            return View(new_comment);
        }

    }



}

这是我的标准生成的强类型视图:

@model test.Models.Comment

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Comment</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.Text)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Text)
            @Html.ValidationMessageFor(model => model.Text)
        </div>

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

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

问题是:当我输入有效数据时,TryUpdateModel()返回true

return View(new Comment());

应该显示空表单,因为传递了新的 Comment 空实例,但它仍然显示具有先前输入的值的表单。

请有人告诉我为什么。如何让它再次显示空表单?

4

1 回答 1

4

清除模型状态:

if (TryUpdateModel(new_comment))
{
    ModelState.Clear();
    return View(new Comment()); //no more problem here
}

所有 HTML 助手在渲染它们的值时首先查看 ModelState,然后才在模型中查看。


或者甚至更好、更正确地使用Redirect-After-Post模式(即在成功 POST 后重定向):

if (TryUpdateModel(new_comment))
{
    return RedirectToAction("Create");
}
于 2012-04-15T09:22:33.933 回答