【问题标题】:MVC Bootstrap PopOver with Server-side Validation带有服务器端验证的 MVC Bootstrap PopOver
【发布时间】:2014-04-21 13:08:22
【问题描述】:

我有一个简单的 MVC 应用程序,它显示一个带有表单的 BootStrap PopOver 模式。我想在提交数据时对表单运行一些服务器端验证。如果检测到错误,我希望应用程序在显示存储在 ModelState 中的任何错误时,保持现有表单打开并保留用户数据。

当我直接在此应用程序中调用“创建”视图时,表单会适当地显示错误。但是,当我将 Create 视图用作模式时,它会显示错误消息,指出存在验证错误,但 ValidationSummary 不会显示错误详细信息。

如何将 ModelState 中的数据返回到视图中?

Models/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; }
}

Controllers/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 });
    }
}

Views/Home/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>

Views/Home/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>
}

【问题讨论】:

    标签: asp.net-mvc twitter-bootstrap modal-dialog asp.net-mvc-5 server-side-validation


    【解决方案1】:

    我确实设法让服务器端验证工作。我仍然希望有人能提出正确、更好或自动魔术的方法来实现这一点。

    如果有人遇到与我相同的困难,这里是我必须进行的代码更改才能使其正常工作。

    控制器更改

    [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);
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多