好吧,我有简单的 ajax 形式:
这是MyPartialView
@using(Ajax.BeginForm("action", "controller", new AjaxOptions
{
OnBegin = "beginRequest",
OnComplete = "completeRequest",
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "div-to-replace"
}, }))
{
<input type="text" id="my-input" />
...
}
这是父视图:
<div id="div-to-replace">
@Html.RenderPartial("MyPartialView")
</div>
在我的控制器中,我有:
[HttpPost]
public ActionResult action(Model model)
{
if (ModelState.IsValid)
{
// do staff with model
// return partial view
return PartialView("MyPartialView");
}
// else add error and return json result
return Json(new {error = "invalid data"});
}
还有我的 ajax 完整方法上的 javascript:
function completeRequest(data) {
var result = $.parseJSON(data.responseText);
if (result != 'undefined' && result != null && result.error) {
// just display error and not replace all content
// attachModelError is my custom method, it just adds vlaidation-error class to inputs, etc.
attachModelError("my-input", result.error);
return;
}
// or show returned html (depending on returned model form inputs will be modified:
// select box with different items in my case
$('#div-to-replace').html(data.responseText);
}
#div-to-replace
但问题是如果模型状态无效,我有空。如果模型状态正常,则一切正常。如果我使用不同的插入模式,它会在 div 之前或之后创建 div 内容的副本。
摘要:
我想要InsertionMode
根据json
结果不同的行为。我不需要替换数据if (result != 'undefined' && result != null && result.error)
。