MVC 异步发布模型和负载响应

hoy*_*tdj 1 c# ajax asp.net-mvc jquery asynchronous

我在一个页面上有 2 个局部视图,每个视图都有自己独特的模型。我想从一个局部视图(它是一个表单)异步发布数据,然后从控制器获取响应并将其加载到第二个局部视图中。

基本上我的页面结构如下。

父视图:

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

_viewA:

@model ModelA

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

_视图B:

@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>
Run Code Online (Sandbox Code Playgroud)

控制器:

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

Javascript:

//I'm not sure...
//Probably some AJAX call
//Then we stick the response into div#viewB
Run Code Online (Sandbox Code Playgroud)

关键是我需要这一切异步发生。用户填写表单点击一个按钮,数据被发送到服务器,响应被返回,部分页面更新,所有都没有回发。

我需要什么 Javascript(和其他更改)才能使这一切正常工作?

谢谢!

Shy*_*yju 5

您可以使用 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">
}
Run Code Online (Sandbox Code Playgroud)

现在使用这个 javascript 来监听提交事件,阻止默认表单提交(因为我们要做一个 ajax 发布),序列化表单并通过$.post方法发送。您可以使用 jQueryserialize方法来获取表单的序列化版本。

$(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);
       });
   });

});
Run Code Online (Sandbox Code Playgroud)