gpt4 book ai didi

json - 从 MVC 5 Controller 返回部分 View 和 JSON

转载 作者:行者123 更新时间:2023-12-02 17:24:41 25 4
gpt4 key购买 nike

在 MVC5 项目中,我打开一个模式对话框,以防万一出现异常,我想打开这个对话框并在这个对话框中的一个 div 上显示一条消息。据我所知,我应该遵循将局部 View 渲染成字符串的方法,但大多数示例在 MVC5 中不起作用,如 Return Partial View and JSON from ASP.NET MVC Action .是否有适用于 MVC5 的类似或更好的方法?

最佳答案

您可以执行以下操作

方案一(使用局部 View )

[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());
}
}

您的部分 View 应如下所示:

<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>

方案二(使用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;
}

希望对你有帮助

关于json - 从 MVC 5 Controller 返回部分 View 和 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39625405/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com