0

フォーム付きの BootStrap PopOver Modal を表示する単純な MVC アプリケーションがあります。データが送信されるときに、フォームに対してサーバー側の検証を実行したいと思います。エラーが検出された場合、ModelState に保存されているエラーを表示しながら、アプリケーションで既存のフォームを開いたままにし、ユーザーのデータを配置したいと考えています。

このアプリケーションで「作成」ビューを直接呼び出すと、フォームにエラーが適切に表示されます。ただし、作成ビューをモーダルとして使用すると、検証エラーがあったことを示すエラー メッセージが表示されますが、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>
}
4

1 に答える 1