【问题标题】:Returning Partialview & JSON from MVC 5 Controller从 MVC 5 控制器返回部分视图和 JSON
【发布时间】:2017-01-30 05:26:13
【问题描述】:

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

【问题讨论】:

  • 您想在模态框上显示错误,而不是显示错误的局部视图吗?
  • 其实我渲染局部视图用于创建、更新等,如果控制器中的创建操作方法有错误,我想渲染_Error局部视图而不是_Create并显示一些消息( _Error 部分视图中的操作方法以 json 形式返回。

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


【解决方案1】:

您可以执行以下操作

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

希望对你有帮助

【讨论】:

  • 非常感谢,我试试看。投票+
  • 实际上不是,但我更喜欢使用另一种方法并在不打开模式对话框的情况下显示 toast 消息。谢谢...
  • toast 消息将仅包含错误,我在您的问题上询问了您的问题 cmets 您想要它如何,我将更新答案
  • @binary 我更新了答案以包含另一个方法
【解决方案2】:

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

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

这将在弹出窗口中加载其自身的部分视图。您不必将其转换为字符串。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-06
    • 2013-09-11
    • 1970-01-01
    • 1970-01-01
    • 2016-01-24
    • 1970-01-01
    相关资源
    最近更新 更多