[英]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.