我在一个页面上有 2 个部分 View ,每个 View 都有自己独特的模型。我想从一个局部 View (它是一种表单)异步发布数据,然后从 Controller 获取响应并将其加载到第二个局部 View 中。
基本上我的页面结构如下。
父 View :
<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>
Controller :
[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(和其他更改)才能使这一切正常工作?
谢谢!
最佳答案
您可以使用 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 来监听提交事件,阻止默认表单提交(因为我们将进行 ajax 发布),序列化表单并通过 $.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);
});
});
});
关于c# - 使用 MVC 的异步发布模型和负载响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40986205/