0

폼이있는 BootStrap PopOver Modal을 표시하는 간단한 MVC 응용 프로그램이 있습니다. 데이터가 제출 될 때 양식에 대해 서버 측 유효성 검사를 실행하고 싶습니다. 오류가 발견되면 ModelState에 저장된 오류를 표시하면서 응용 프로그램에서 사용자의 데이터로 기존 양식을 열어 두는 것이 좋습니다.서버 측 유효성 검사가 포함 된 MVC 부트 스트랩 PopOver

이 응용 프로그램에서 직접 "만들기"보기를 ​​호출하면 양식에 오류가 적절하게 표시됩니다. 그러나 Create 뷰를 모달로 사용하면 유효성 검사 오류가 있음을 나타내는 오류 메시지가 표시되지만 ValidationSummary는 오류 세부 정보를 표시하지 않습니다.

ModelState에서보기로 데이터를 다시 가져올 수 있습니까?

모델/MyViewModel.cs

public class MyViewModel 
{ 
    [Display(Name = "Field #1")] 
    public string Field1 { get; set; } 

    [Required(ErrorMessage = "Field2 is required.")] 
    [StringLength(10)] 
    [Display(Name = "Field #2")] 
    public string Field2 { get; set; } 
} 

컨트롤러/HomeController.cs

public class HomeController : Controller 
{ 
    public ActionResult Index() 
    { 
     return View(); 
    } 

    public ActionResult Create() 
    { 
     var data = new MyViewModel {Field1 = "This is field 1!"}; 
     return PartialView("Create", data); 
    } 

    [HttpPost] 
    public ActionResult Create(MyViewModel model) 
    { 
     if (!ModelState.IsValid) 
     { 

      // There were validation errors. Don't lose the data the user entered on the page. 
      // Do I need to return the modelstate here? 
      return PartialView(model); 
     } 

     return Json(new { success = true }); 
    } 
} 

조회수/홈/Index.chstml

@Html.ActionLink("Open the popover modal", "create", null, null, new { id = "modalLink" }) 
@Html.ActionLink("Navigate directly to the modal page", "Create", "Home") 

    <script type="text/javascript"> 
     $(function() { 
     $('#modalLink').click(function() { 
      $('#dialog').load(this.href, function() { 
      $('#simpleModal').modal('show'); 
      bindForm(this); 
      }); 
      return false; 
     }); 
     }); 

     function bindForm(dialog) { 
     $('form', dialog).submit(function() { 
      $.ajax({ 
      url: this.action, 
      type: this.method, 
      data: $(this).serialize(), 
      success: function (result) { 
       if (result.success) { 
       alert('Validation was successful.'); 
       $('#simpleModal').modal('hide'); 
       } else { 
       // Am I missing something here? 
       alert('Server validation failed!'); 
       } 
      } 
      }); 
      return false; 
     }); 
     } 
    </script> 

조회수/홈/Create.cshtml

@model MvcModalPopupWithValidation.Models.MyViewModel 

@using (Html.BeginForm()) 
{ 
    <div class="modal fade" id="simpleModal" tabindex="-1" role="dialog" aria-labelledby="simpleModalLabel" aria-hidden="true"> 
    <div class="modal-dialog"> 
     <div class="modal-content"> 
     <div class="modal-header"> 
      <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> 
      <h4 class="modal-title" id="simpleModalLabel"> 
      Modal Validation Test 
      </h4> 
     </div> 
     <div class="modal-body"> 
      @Html.ValidationSummary(true) 

      <div> 
      @Html.LabelFor(x => x.Field1) 
      @Html.EditorFor(x => x.Field1) 
      @Html.ValidationMessageFor(x => x.Field1) 
      </div> 
      <div> 
      @Html.LabelFor(x => x.Field2) 
      @Html.EditorFor(x => x.Field2) 
      @Html.ValidationMessageFor(x => x.Field2) 
      </div> 

     </div> 
     <div class="modal-footer"> 
      <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> 
      <button type="submit" class="btn btn-primary" id="btnDeclineModal">Save changes</button> 
     </div> 
     </div> 
    </div> 
    </div> 
} 

답변

1

I는 서버 측 유효성 검사가 작동하도록하기 위해 관리 않았다. 나는 아직도 누군가가 이것을 달성하기 위해 정확하고, 더 좋거나, 자동 마법 같은 방법을 택할 수 있기를 바라고있다.

누구나 똑같은 어려움을 겪고있는 경우, 제대로 작동하려면 코드 변경이 필요합니다.

컨트롤러 변경

[HttpPost] 
public ActionResult Create(MyViewModel model) 
{ 
    if (!ModelState.IsValid) 
    { 
     var errors = new List<string>(); 

     foreach (var modelState in ViewData.ModelState.Values) 
     { 
      errors.AddRange(modelState.Errors.Select(error => error.ErrorMessage)); 
     } 

     return Json(errors); 
    } 

    return Json(new { success = true }); 
} 

Create.cshtml 변경

<div id="errorContainer" class="alert alert-danger" style="display: none"> 
    Validation issues: 
    <div id="errors"></div> 
    </div> 

Index.cshtml 변경

function bindForm(dialog) { 
    $('form', dialog).submit(function() { 
     $.ajax({ 
     url: this.action, 
     type: this.method, 
     //traditional: true, 
     data: $(this).serialize(), 
     success: function (result) { 
      if (result.success) { 
      showValidationErrors(false); 
      $('#simpleModal').modal('hide'); 
      alert('Validation was successful.'); 
      } else { 
      fillErrorList(result); 
      showValidationErrors(true); 
      } 
     } 
     }); 
     return false; 
    }); 

    function showValidationErrors(isShown) { 
     if (isShown) { 
     $("#errorContainer").show(); 
     } else { 
     $("#errorContainer").hide(); 
     } 
    } 

    function fillErrorList(errors) { 
     $("#errors").html(""); 

     var list = document.createElement('ul'); 

     for (var i = 0; i < errors.length; i++) { 
     var item = document.createElement('li'); 
     item.appendChild(document.createTextNode(errors[i])); 
     list.appendChild(item); 
     } 
     $("#errors").html(list); 
    } 
관련 문제