2016-12-06 49 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