MVC3 View does not display blank form when validating

Very simple situation, here is my model:

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

}

Here is my controller:

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

    }



}

And here my standard generates a strongly typed view:

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

Problem : when you enter valid data, it TryUpdateModel()returns trueand

return View(new Comment());

should display an empty form because a new empty instance of the comment is being transmitted, but it still displays the form with the values ​​entered earlier.

Please tell me why. How to display an empty form again?

+3
source share
1 answer

Clear Model State:

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

All HTML helpers first look at ModelState when rendering their values, and only after that in the model.


Redirect-After-Post (.. POST):

if (TryUpdateModel(new_comment))
{
    return RedirectToAction("Create");
}
+4

All Articles