【发布时间】:2013-02-15 06:34:49
【问题描述】:
有没有办法在 asp.net mvc 中提交部分视图表单而不重新加载父页面,但仅将部分视图重新加载到其新状态?类似于 knockout.js 使用数据绑定进行更新的方式。
我的数据表使用可变数量的列/名称呈现,所以我不认为 knockout.js 是这个选项的一个选项,所以我尝试使用部分视图。
【问题讨论】:
标签: asp.net-mvc jquery knockout.js partial-views
有没有办法在 asp.net mvc 中提交部分视图表单而不重新加载父页面,但仅将部分视图重新加载到其新状态?类似于 knockout.js 使用数据绑定进行更新的方式。
我的数据表使用可变数量的列/名称呈现,所以我不认为 knockout.js 是这个选项的一个选项,所以我尝试使用部分视图。
【问题讨论】:
标签: asp.net-mvc jquery knockout.js partial-views
没有 jQuery。
你要做的就是把你的 Partial 放在一个 div 中,比如:
<div id="partial">
@Html.Partial("YourPartial")
</div>
然后,要更新(例如单击 ID 为 button 的按钮),您可以这样做:
$("#button").click(function () {
$.ajax({
url: "YourController/GetData",
type: "get",
data: $("form").serialize(), //if you need to post Model data, use this
success: function (result) {
$("#partial").html(result);
}
});
})
那么您的操作将类似于:
public ActionResult GetData(YourModel model) //that's if you need the model
{
//do whatever
return View(model);
}
【讨论】:
实际上,如果您的 Partial 具有子操作方法,您可以直接发布(甚至使用锚链接)到子操作并获得类似 Ajax 的效果。我们在多个视图中执行此操作。
语法是
@Html.Action("MyPartial")
子动作是
public ActionResult MyPartial()
{
return PartialView(Model);
}
如果您的表单发布到子操作
@using (Html.BeginForm("MyPartial"))
{
...
}
部分视图将使用从子操作返回的部分视图进行更新。
Jquery 仍然是更新部分的合法方式。但从技术上讲,您的问题的答案是肯定的。
【讨论】:
Html.BeginForm("string") 调用扩展重载 BeginForm(this HtmlHelper htmlHelper, object routeValues) 并导致 POST /?Length=N。我觉得这个答案“有效”是无意的行为。
对于使用局部视图和@html.RenderPartial("partialName") 的此类场景,我会使用 Ajax 表单助手 partial helpers
【讨论】:
通常我在寻找这样的东西时发现人们提供的信息太有限,所以我会在这里尝试提供帮助。关键是设置一个带有 ID 的 div,您可以将返回的 html 附加到该 ID。此外,当您点击控制器时,请确保它返回部分。这种方法存在一些潜在问题,但如果天气好的话,它应该可以工作。
<div id="CategoryList" class="widget">
@{
Html.RenderPartial("WidgetCategories.cshtml");
}
</div>
function DeleteCategory(CategoryID) {
$.get('/Dashboard/DeleteWidgetCategory?CategoryID=' + CategoryID,
function (data) {
if (data == "No") {
alert('The Category has report widgets assigned to it and cannot be deleted.');
}
else {
$('#CategoryList').html(data);
}
}
);
}
[HttpGet("DeleteWidgetCategory")]
[HttpPost("DeleteWidgetCategory")]
public IActionResult DeleteWidgetCategory(string CategoryID)
{
string Deleted = CategoryModel.DeleteCategory(CategoryID);
if (Deleted == "Yes")
{
return PartialView("WidgetCategories");
}
else
{
return this.Json("No");
}
}
【讨论】:
在您的主视图中
<div id=SearchResult>
@Html.Partial("_NameOfPartialView", Model)
</div>
<input type="button" id="btnSubmit" value="Submit">
在您的 Javascript 文件中
$('#btnSubmit').click(function () {
GetData(Id);
});
function GetData(Id){
$.ajax({
url: "/Home/GetEmployee/",
type: "get",
data: { Id:Id },
success: function (result) {
$('#SearchResult').html(result);
}
});
}
在您的家庭控制器中
public ActionResult GetEmployee(int Id)
{
var employee= context.Employee.Where(x=> x.EmployeeId == Id)
return this.PartialView("_NameOfPartialView", employee);
}
【讨论】: