2016-12-06 51 views
0

我在單個頁面上有2個部分視圖,每個視圖都有自己獨特的模型。我想異步地發佈來自一個局部視圖(它是一個形式)的數據,然後從控制器獲取響應並將其加載到第二個局部視圖中。使用MVC異步發佈模型和負載響應

基本上我的頁面結構如下。

父視圖:

<div id="viewA"> 
    @Html.Partial("_viewA, Model.viewA) 
</div> 
<div id="viewB"> 
    <p>Loading...</p> 
</div> 

_viewA:

@model ModelA 

@using (Html.BeginForm()) 
{ 
    @Html.LabelFor(model => model.Thing) 
    @Html.EditorFor(model => model.Thing) 
    <input type="submit" value="Submit"> 
} 

_viewB:

@model ModelB 

<table> 
    <tr> 
     <th> 
      Column 1 
     </th> 
     <th> 
      Column 2 
     </th> 
    </tr> 
    @foreach (var item in Model) { 
    <tr> 
     <td> 
      @Html.DisplayFor(modelItem => item.Col1) 
     </td> 
     <td> 
      @Html.DisplayFor(modelItem => item.Col2) 
     </td> 
    } 
</table> 

控制器:

[HttpPost] 
public ActionResult Something([Bind(Include="Thing")] ModelA modela) 
{ 
    //do stuff 
    ModelB modelb = new ModelB(); 
    return PartialView("_viewB", modelb); 
} 

Javascript:

//I'm not sure... 
//Probably some AJAX call 
//Then we stick the response into div#viewB 

關鍵是我需要這一切發生異步。用戶填寫表單點擊一個按鈕,數據發送到服務器,返回響應,部分頁面更新,全部沒有回發。

需要什麼Javascript(以及其他更改)才能使這一切正常工作?

謝謝!

回答

1

您可以使用ajax提交表單,並在ajax調用的響應回調時根據需要更新DOM。

因此,讓我們添加一個Id到表單元素,我們可以使用但是把AJAX行爲

@using (Html.BeginForm("Something","Student",FormMethod.Post,new { id="studForm"})) 
{ 
    @Html.LabelFor(model => model.Thing) 
    @Html.EditorFor(model => model.Thing) 
    <input type="submit" value="Submit"> 
} 

現在使用這個JavaScript監聽提交事件,阻止默認的形式提交(我們打算做一個阿賈克斯職位),序列化表格,並通過$.post方法發送。您可以使用jQuery serialize方法獲取表單的序列化版本。

$(function(){ 

    $("#studForm").submit(function(e){ 
     e.preventDefault(); //prevent normal form submission 

     var actionUrl = $(this).attr("action"); // get the form action value 
     $.post(actionUrl ,$(this).serialize(),function(res){ 
      //res is the response coming from our ajax call. Use this to update DOM 
      $("#viewB").html(res); 
     }); 
    }); 

}); 
+0

工作就像一個魅力!謝謝! – hoytdj