2012-03-28 52 views
0

我有一個顯示部分視圖的jquery模式對話框。部分視圖包含一個表單,可以回傳看看輸入的值是否有效。我想要的是我在控制器中返回的錯誤消息,以在不刷新頁面的情況下顯示在局部視圖上。我該如何做到這一點?jQuery模態對話框和MVC3部分視圖

管窺:

@model SimpleSalon.Data.Models.GiftCard 

    @using (Html.BeginForm("AddGiftCard", "Sales", FormMethod.Post, new { @class="addGiftCardForm" })) 
    { 
     @Html.ValidationSummary("Correct the errors below:") 

     <table> 
      <tr> 
       <td>Card Number</td> 
       <td>@Html.TextBoxFor(x => x.CardNumber)</td> 
      </tr> 
      <tr> 
       <td>Amount</td> 
       <td>@Html.TextBoxFor(x => x.InitialBalance)</td> 
      </tr> 
     </table> 
    } 

控制器:

[HttpPost] 
    public ActionResult AddGiftCard(GiftCard model) 
    { 
     if (ModelState.IsValid) 
     { 
      //if it's valid in the db continue on 
      //else ModelState.AddModelError("", "card number not valid.") 
     } 

     return View(model); 
    } 

提前感謝!

回答

0

你可以使用的Ajax.BeginForm,而不是Html.BeginForm

@using (Ajax.BeginForm("AddGiftCard", "Sales", null, new AjaxOptions { UpdateTargetId = "container" }, new { @class="addGiftCardForm" })) 
{ 
    ... 
} 

注意,我在AjaxOptions使用UpdateTargetId = "container"。這意味着由AddGiftCard操作返回的部分結果將被注入到具有id="container"的DOM元素中。所以確保你把這個元素包裝在jQuery對話框中。

而且這個工作確保你已經提到的jquery.unobtrusive-ajax.js腳本到你的頁面:

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script> 
+0

我的印象是,已不再推薦使用Ajax的方法,以及使用jQuery $就是首選 – 2012-03-28 17:10:08

+0

所以我現在已經有了正確的ajax回發工作。添加模型狀態錯誤時,我的控制器代碼應該如何查看?我是否返回PartialViewResult? – 2012-03-28 17:43:26