MVC3 View在传递验证时不显示空表单

时间:2012-04-15 09:20:05

标签: asp.net-mvc asp.net-mvc-3 razor

非常简单的情况,这是我的模特:

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());

应显示空表单,因为会传递新的空实例,但它仍会显示前面输入的值的表单。

请有人告诉我原因。如何让它再次显示空格?

1 个答案:

答案 0 :(得分: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");
}