2012-04-15 33 views
3

很简单的情况,这里是我的模型:MVC3查看显示`吨空的形式传递

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

    } 



} 

,这里是我的旗genered strongly-类型的视图:

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

问题是:当我进入VA盖资料,TryUpdateModel()回报true

return View(new Comment()); 

应显示空的形式,因为评论的新的空实例传递,但它仍然显示形式值之前输入。

请有人告诉我为什么。如何使它再次显示空格式?

回答

4

清除的ModelState:

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"); 
} 
+0

真的didn't了解的ModelState和ModelState.Clear()。非常感谢你! – Roman 2012-04-15 09:32:08