有没有一种方法可以在不重新加载父页面的情况下提交asp.net mvc中的部分视图表单,但仅重新加载部分视图以达到其新状态?类似于knockout.js使用data-bind更新的方式。
我的数据表呈现具有可变数量的列/名称,因此我认为knockout.js对于这个问题不是一个选项,因此我正在尝试使用部分视图。
我的数据表呈现具有可变数量的列/名称,因此我认为knockout.js对于这个问题不是一个选项,因此我正在尝试使用部分视图。
不能没有jQuery。
您需要做的是将您的部分视图放在一个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
的结果。我觉得这个答案的“有效性”是没有预期的行为。 - Jasen<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">
$('#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);
}