폼이있는 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">×</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>
}