[英]How to replace div's content by partial view or update it's content depending on what json result returns on ajax complete?
好吧,我有简单的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)
。
很久以前我不得不解决这个问题。 我提出了一个简单的解决方案,今天可能不是最好的解决方案,但它可以完成工作。
我的解决方案涉及设置一个控制器操作,该操作只使用它需要的数据呈现部分,并让我的JavaScript请求它。
C#
MyController: Controller
{
public ActionResult GetPartialViewAction()
{
return PartialView("mypartialview", new partialViewModel());
}
}
JavaScript的
$.ajax({
url: "/my/getpartialaction/"
}).done(function(data) {
$("#partialViewDiv").html(data);
});
HTML
<div id="partialViewDiv"></div>
更好的解决方案是使用MVVM / MVC JavaScript库,它允许您利用html模板,只需通过ajax解决方案传输数据。 我建议查看knockout.js或backbone.js以获得更多可接受的模式。
我对默认的c#ajax表单有同样的问题。 我有一个可行的解决方案。
jQuery的:
$(function () {
var ajaxFormSubmit = function () {
var $form = $(this);
var options = {
url: $form.attr("action"),
type: $form.attr("method"),
data: $form.serialize(),
cache: false
}
$.ajax(options).done(function (data) {
data.replaces.each(function (replace) {
$(replace.id).replaceWith(replace.html);
});
});
return false;
};
$("form[data-ajax='true']").submit(ajaxFormSubmit);});
form.cshtml
@using (Html.BeginForm("Create", "Menu", FormMethod.Post, new { data_ajax = "true" }))
{}
模型样本
public string Id {get;set;}
public string Html {get;set;}
你需要在控制器中做的最后一件事是返回一个带有模型样本列表的json结果,id是要更新的目标元素,对于html,你必须使用render partial /或view作为字符串。
对于渲染视图,请参阅[问题]: https : //stackoverflow.com/questions/434453
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.