2012-07-20 86 views
1

我在玩jQuery UI和PartialViews,並遇到了問題,我無法安靜地把我的頭轉過來。從部分行動返回部分視圖到特定的div

該位工作如我所料:

<div> 
    @Ajax.ActionLink("Test Me!", "dialogtest", new { id = Model.Id }, new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "dialogtest-view" })</td> 
</div> 
<div id="dialogtest-view"> 
</div> 

這得到這種操作方法

[HttpGet] 
public PartialViewResult DialogTest(int id) 
{ 
    //pretend to get something from DB here 
    var vm = new DialogUITestVM(); 
    return PartialView("uidialog_partial", vm); 
} 

,並返回我這顯示在目標DIV一個PartialView。 jQuery + jQueryUI用於將這個div彈出爲模態對話框。第一部分測試完成!

行,所以現在我們說的PartialView返回的只是一個基本形式的文本框,沿着線的東西:

@using (Html.BeginForm("DialogTest", "pages", FormMethod.Post)) 
{ 
    @Html.HiddenFor(x => x.Id) 
    @Html.TextBoxFor(x => x.Name) 
    <button type="submit">Test Me!</button> 
} 

這是POSTd回精控制器 -

[HttpPost] 
public ActionResult DialogTest(DialogUITestVM vm) 
{ 
    //arbitrary validation so I can test pass and fail) 
    if (vm.Name.Equals("Rob")) 
    { 
     //error! 
     vm.ErrorMessage = "There was an error you numpty. Sort it out."; 
     return PartialView(vm); 
    } 

    //hooray it passed - go back to index 
    return RedirectToAction("index"); 
} 

但是,如果我讓動作失敗了驗證,而不是再次將PartialView定位到div,它會重新繪製整個頁面(顯然會丟失jQuery UI對話框)。

我想要的是:如果驗證失敗,只需更新包含表單的div

我哪裏錯了?

回答

2

你可以在你的部分使用Ajax的形式,而不是一個正常的形態和你的AjaxOptions使用的onSuccess回調:

@using (Ajax.BeginForm("DialogTest", "pages", new AjaxOptions { UpdateTargetId = "dialogtest-view", OnSuccess = "success" })) 
{ 
    @Html.HiddenFor(x => x.Id) 
    @Html.TextBoxFor(x => x.Name) 
    <button type="submit">Test Me!</button> 
} 

,然後分別修改控制器動作:

[HttpPost] 
public ActionResult DialogTest(DialogUITestVM vm) 
{ 
    //arbitrary validation so I can test pass and fail) 
    if (vm.Name.Equals("Rob")) 
    { 
     //error! 
     vm.ErrorMessage = "There was an error you numpty. Sort it out."; 
     return PartialView(vm); 
    } 

    //hooray it passed - go back to index 
    return Json(new { redirectUrl = Url.Action("Index") }); 
} 

和當然在javascript文件中定義相應的成功回調:

function success(result) { 
    if (result.redirectUrl) { 
     window.location.href = result.redirectUrl; 
    } 
} 
+0

工作的gr吃,謝謝。唯一的區別是我不得不使用$ .parseJSON來獲取重定向url。 – glosrob 2012-07-20 22:24:08