2012-04-15 8 views
3

非常にシンプルな状況を通過し、検証に表示空のフォームをdoesnの `t、ここで私のモデルである:ここでは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

を本当ににModelStateとModelState.Clear(知っているdidn'tの)。どうもありがとうございました! – Roman

関連する問題