Dmy*_*tro 4 c# asp.net-mvc jquery json
好吧,我有简单的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" />
...
}
Run Code Online (Sandbox Code Playgroud)
这是父视图:
<div id="div-to-replace">
@Html.RenderPartial("MyPartialView")
</div>
Run Code Online (Sandbox Code Playgroud)
在我的控制器中我有:
[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"});
}
Run Code Online (Sandbox Code Playgroud)
和我在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);
}
Run Code Online (Sandbox Code Playgroud)
但问题是#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());
}
}
Run Code Online (Sandbox Code Playgroud)
JavaScript的
$.ajax({
url: "/my/getpartialaction/"
}).done(function(data) {
$("#partialViewDiv").html(data);
});
Run Code Online (Sandbox Code Playgroud)
HTML
<div id="partialViewDiv"></div>
Run Code Online (Sandbox Code Playgroud)
更好的解决方案是使用MVVM/MVC JavaScript库,它允许您利用html模板,只需通过ajax解决方案传输数据.我建议查看knockout.js或backbone.js以获得更多可接受的模式.
| 归档时间: |
|
| 查看次数: |
14785 次 |
| 最近记录: |