在我的asp.net MVC 4项目中,我喜欢从局部视图中保护某些内容,即当用户点击“更多详细信息”时。 保存数据没问题,关闭局部视图没问题,打开局部视图不是问题,这是我的模型无效时(当用户忘记标记的时候) 结果是我的部分视图被返回,但不在视图内部。它只被视为独立页面。
查看:
@model Evaluatietool.ViewModels.EvaluatorWijzigenOPViewModel
<h3>@ViewBag.Message</h3>
@using (Html.BeginForm("ChangeEvaluator", "Ontwikkelplan"))
{
@Html.ValidationSummary(true)
@Html.HiddenFor(model => model.oldEvalAccount)
@Html.HiddenFor(model => model.selectedMedewerkerAccount)
@Html.HiddenFor(model => model.eval);
@Html.HiddenFor(model => model.countMedewerkers);
...
...
<div class="Buttons">
<input type="submit" value="Submit" />
@Ajax.ActionLink("Sluiten", "Evaluatorenlijst", new AjaxOptions { OnSuccess = "HideResultDiv" })
</div>
}
控制器:
[HttpPost]
public ActionResult ChangeEvaluator(EvaluatorWijzigenOPViewModel ewopvm)
{
if (ModelState.IsValid)
{
if (ewopvm.selectedObjects != null)
{
ewopvm.selectedObjects.Add(ewopvm.selectedMedewerkerAccount);
}
else
{
ewopvm.selectedObjects = new List<string>();
ewopvm.selectedObjects.Add(ewopvm.selectedMedewerkerAccount);
}
Ontwikkelplannen op = new Ontwikkelplannen();
Evaluaties e = new Evaluaties();
foreach (string s in ewopvm.selectedObjects)
{
op.ChangeEvaluator(ewopvm.newEvalAccount, ewopvm.oldEvalAccount, s, ewopvm.eval);
}
return RedirectToAction("Evaluatorenlijst");
}
return PartialView("EvaluatorWijzigenPartial", ewopvm);
}
调用部分视图的链接
@Ajax.ActionLink(item.Evaluator1.Naam, "EvaluatorWijzigenPartial", new { id = item.ID, eval = true }, new AjaxOptions { UpdateTargetId = "EvaluatorWijzigen", OnComplete = "ShowResultDiv"})
答案 0 :(得分:11)
从我可以看到,您正在使用标准Html.BeginForm
POST到ChangeEvaluator
控制器操作,该操作执行重定向或在验证失败时返回部分视图。
所以你观察到的行为是完全正常的。如果你想实现这个目的,你必须使用AJAX提交这个表格:
@using (Ajax.BeginForm("ChangeEvaluator", "Ontwikkelplan", new AjaxOptions { OnSuccess = "handleSuccess" }))
{
...
}
然后您可以调整您的控制器操作,以便在成功的情况下它不会重定向但它返回一个包含要重定向到的URL的Json对象:
[HttpPost]
public ActionResult ChangeEvaluator(EvaluatorWijzigenOPViewModel ewopvm)
{
if (ModelState.IsValid)
{
...
return Json(new { redirectTo = Url.Action("Evaluatorenlijst") });
}
return PartialView("EvaluatorWijzigenPartial", ewopvm);
}
最后编写handleSuccess
javascript函数:
function handleSuccess(result) {
if (result.redirectTo) {
// The controller action returned a JSON object with the redirectTo property
// let's redirect to this location:
window.location.href = result.redirectTo;
} else {
// The controller action returned a partial view with the form and the errors
// So we need to update some containing DIV with it:
$('#someDivThatCOntainsYourForm').html(result);
}
}