2016-09-21 123 views
2

在一個MVC5項目中,我打開一個模式對話框,如果發生異常,我想打開此對話框並在此對話框的div上顯示消息。據我所知,我應該按照這種方法將partialview渲染爲一個字符串,但大多數示例在MVC5中不起作用,如Return Partial View and JSON from ASP.NET MVC Action。是否有任何類似或更好的方法適用於MVC5?從MVC 5控制器返回部分視圖和JSON

+1

你想顯示模態上的錯誤,而不是錯誤的自我錯誤的部分視圖嗎? – Monah

+0

其實我呈現了創建,更新等的部分視圖,如果在控制器的Create操作方法中有錯誤,我想呈現_Error partialview而不是_Create並顯示一些消息(從操作方法返回爲json )在_Error partialview中。 –

回答

2

你可以做以下

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

希望這會幫助你

+0

非常感謝,我會試一試。投票+ –

+0

@binary是否與你合作? – Monah

+0

實際上並不是,但我更喜歡使用其他方法並在不打開模式對話框的情況下顯示Toast消息。謝謝... –

0

這是一個有效的例子,我多次使用這種技術。 如果它是一個簡單的獲取調用,比我建議做一個你想要顯示的數據的局部視圖,並通過jQuery與下面的代碼調用它。

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

這將在彈出窗口中加載部分視圖。你不必將其轉換爲字符串。