2

MVC5プロジェクトではモーダルダイアログを開き、例外がある場合はこのダイアログを開き、このダイアログのdivにメッセージを表示します。私の知る限りでは、partialviewを文字列に変換する方法に従うべきですが、ほとんどの例はMVC5ではReturn Partial View and JSON from ASP.NET MVC Actionとしては機能しません。 MVC5のために働く同様のアプローチやより良いアプローチはありますか?PartialviewとJSONをMVC 5コントローラから返す

+1

あなたはモーダルでエラーを表示したいのですが、 – Monah

+0

実際には、create、updateなどの部分ビューをレンダリングします。コントローラのCreateアクションメソッドにエラーがある場合、_Createの代わりに_Error partialviewをレンダリングし、いくつかのメッセージを表示します(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> 

(JSONを使用して)解決策2

あなたの行動

[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

実際はそうではありませんが、別のアプローチを使用し、モーダルダイアログを開かずにトーストメッセージを表示することをお勧めしました。ありがとう... –

0

これは有効な例です。このテクニックは何度も使用されています。 シンプルなget呼び出しよりも、表示したいデータの部分的な表示をし、jqueryを使って以下のコードで呼び出すことをお勧めします。

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

これは、部分的な表示をポップアップで読み込みます。それを文字列に変換する必要はありません。

関連する問題