2

MVC5 프로젝트에서 모달 대화 상자를 열고 예외가있는 경우이 대화 상자를 열고이 대화 상자에서 div에 메시지를 표시하려고합니다. 지금까지 보았 듯이 partialview를 문자열로 렌더링하는 방법을 따라야하지만 대부분의 예제는 MVC5에서 Return Partial View and JSON from ASP.NET MVC Action과 같이 작동하지 않습니다. MVC5에서 유사하거나 더 나은 접근 방식이 있습니까?MVC 5 컨트롤러에서 Partialview 및 JSON 반환

+1

당신은 모달에 오류를 보여주고 싶습니다. – Monah

+0

실제로 생성, 업데이트 등에 대한 부분 뷰를 렌더링하고 컨트롤러의 만들기 작업 메서드에 오류가있는 경우 _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

이것은 유효한 예입니다.이 기술을 여러 번 사용했습니다. 만약 내가 간단한 코드를 호출하는 것이 좋습니다 데이터의 부분보기를 만들고 jquery 아래의 코드를 통해 호출하고 싶습니다.

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

이렇게하면 부분보기 자체가 팝업에로드됩니다. 문자열로 변환 할 필요가 없습니다.

관련 문제