本文介绍了返回Partialview&来自MVC 5控制器的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在MVC5项目中,我打开一个模式对话框,如果有异常,我想打开该对话框并在此对话框的div上显示一条消息.据我所知,我应该遵循将部分视图呈现为字符串的方法,但是大多数示例在MVC5中均不起作用,如.是否有类似或更好的方法可用于MVC5?
In an MVC5 project, I open a modal dialog and in case there is an exception, I want to open this dialog and display a message on a div in this dialog. As far as I see, I should follow the approach as rendering partialview into a string, but most of the examples does not work in MVC5 as on Return Partial View and JSON from ASP.NET MVC Action. Is there any similar or better approach working for MVC5?
推荐答案
您可以执行以下操作
解决方案1(使用局部视图)
[HttpPost]
public ActionResult YourAction(YourModel model)
{
if(model!=null && ModelState.IsValid)
{
// do your staff here
Response.StatusCode = 200; // OK
return PartialView("ActionCompleted");
}
else
{
Response.StatusCode = 400; // bad request
// ModelState.ToErrors() : is an extension method that convert
// the model state errors to dictionary
return PartialView("_Error",ModelState.ToErrors());
}
}
您的局部视图应如下所示:
Your partial view should look like:
<div id="detailId">
<!-- Your partial details goes here -->
....
<button type="submit" form="" value="Submit">Submit</button>
</div>
您的脚本
<script>
$(document).ready(function(){
$('#formId').off('submit').on('submit', function(e){
e.preventDefault();
e.stopPropagation();
var form = $('#formId');
$.ajax({
url: form.attr('action'),
data: form.serialize(),
method: 'post',
success : function(result){
$('#detailId').replaceWith(result);
// another option you can close the modal and refresh your data.
},
error: function(data, status, err){
if(data.status == 400){
$('#detailId').replaceWith(data.responseText);
}
}
});
});
});
</script>
解决方案2(使用Json)
采取行动
[HttpPost]
public ActionResult YourAction(YourModel model)
{
if(model!=null && ModelState.IsValid)
{
// do your staff here
return Json(new {status = 200,
//...any data goes here... for example url to redirect
url=Url.Content("YourRedirectAction","Controller")},
}
else
{
return Json( new {status= 400,errors = ModelState.ToErrors()});
}
}
您的脚本应该像
<script>
$(document).ready(function(){
$('#formId').off('submit').on('submit', function(e){
e.preventDefault();
e.stopPropagation();
var form = $('#formId');
$.ajax({
url: form.attr('action'),
data: form.serialize(),
method: 'post',
success : function(result){
if(result.status==200) { // OK
// you might load another action or to redirect
// this conditions can be passed by the Json object
}
else{ // 400 bad request
// you can use the following toastr based on your comment
// http://codeseven.github.io/toastr/demo.html
var ul = $('<ul>')
for(var error in result.errors)
{
ul.append('<li><b>' + error.Key + '</b>:' + error.Value + '</li>;
}
toastr["warning"](ul[0].outerHTML);
}
}
});
});
});
</script>
最后,如果要扩展名ModelState.ToErrors()
public static IEnumerable ToErrors(this ModelStateDictionary modelState)
{
if (!modelState.IsValid)
{
return modelState.ToDictionary(kvp => kvp.Key,
kvp => kvp.Value.Errors
.Select(e => e.ErrorMessage).First())
.Where(m => m.Value.Count() > 0);
}
return null;
}
希望这对您有帮助
这篇关于返回Partialview&来自MVC 5控制器的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!