返回部分视图&来自MVC 5 Controller的JSON

时间:2016-09-21 19:51:44

标签: json ajax asp.net-mvc asp.net-mvc-4 asp.net-mvc-partialview

在MVC5项目中,我打开一个模态对话框,如果有异常,我想打开这个对话框并在这个对话框的div上显示一条消息。据我所知,我应该遵循这种方法将部分视图呈现为字符串,但大多数示例在MVC5中不像Return Partial View and JSON from ASP.NET MVC Action那样有效。是否有类似或更好的方法适用于MVC5?

2 个答案:

答案 0 :(得分:4)

您可以执行以下操作

解决方案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());
    }
}

您的部分视图应如下所示:

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

希望这会对你有所帮助

答案 1 :(得分:0)

这是一个有效的例子,我多次使用过这种技术。 如果它是一个简单的get调用,那么我会建议你显示你要显示的数据的部分视图,并通过jquery用下面的代码调用它。

$( "#result" ).load("@Url.Action("Account","HelloPartial")");

这将在弹出窗口中加载部分视图。你不必将它转换为字符串。