从 MVC 5 控制器返回 Partialview & JSON
Returning Partialview & JSON from MVC 5 Controller
在一个 MVC5 项目中,我打开一个模态对话框,以防出现异常,我想打开这个对话框并在这个对话框的 div 上显示一条消息。据我所知,我应该遵循将局部视图呈现为字符串的方法,但大多数示例在 MVC5 中无法正常工作,如 Return Partial View and JSON from ASP.NET MVC Action。是否有适用于 MVC5 的类似或更好的方法?
这是一个有效的例子,我已经多次使用这种技术。
如果这是一个简单的 get 调用,我建议您对要显示的数据进行部分查看,然后使用下面的代码通过 jquery 调用它。
$( "#result" ).load("@Url.Action("Account","HelloPartial")");
这将在弹出窗口中加载局部视图。您不必将其转换为字符串。
您可以执行以下操作
方案一(使用局部视图)
[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());
}
}
您的部分视图应如下所示:
<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;
}
希望对您有所帮助
在一个 MVC5 项目中,我打开一个模态对话框,以防出现异常,我想打开这个对话框并在这个对话框的 div 上显示一条消息。据我所知,我应该遵循将局部视图呈现为字符串的方法,但大多数示例在 MVC5 中无法正常工作,如 Return Partial View and JSON from ASP.NET MVC Action。是否有适用于 MVC5 的类似或更好的方法?
这是一个有效的例子,我已经多次使用这种技术。 如果这是一个简单的 get 调用,我建议您对要显示的数据进行部分查看,然后使用下面的代码通过 jquery 调用它。
$( "#result" ).load("@Url.Action("Account","HelloPartial")");
这将在弹出窗口中加载局部视图。您不必将其转换为字符串。
您可以执行以下操作
方案一(使用局部视图)
[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());
}
}
您的部分视图应如下所示:
<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;
}
希望对您有所帮助