模态和表单验证

时间:2016-12-15 15:48:12

标签: asp.net asp.net-mvc

我有一个页面,其中有大约4种不同的形式嵌套在他们自己的模态弹出窗口中。

到目前为止,我每个表单只做过一页。

当我提交给控制器并且我的modelState无效时,会发生回到我的局部视图的情况。

如何在我的模态中显示@validationFor消息,就像在我的单个表单页面上一样?基本上页面不会改变,但如果确实如此,它将返回页面,模态仍在运行。

这是否需要我使用某种Ajax调用?那里有什么例子吗?我很确定这可能是一个重复的线程,但是我找不到任何自己的资源。

3 个答案:

答案 0 :(得分:1)

是的,这需要一些javascript来完成这项工作。

  1. 创建部分视图以保存表单。
  2. 
    
    @using (Html.BeginForm("CreateHighSchoolType", "HighSchool", FormMethod.Post, new { id = "CreateHighSchoolTypeForm" }))
    {
        @Html.ValidationSummary(true)
        <fieldset>
            <legend></legend>
            <div class="editor-label">
                @Html.LabelFor(model => model.Name)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.Name)
                @Html.ValidationMessageFor(model => model.Name)
            </div>
            <p>
                <input type="submit" value="Create" id="CreateHighSchoolTypeButton" />
            </p>
        </fieldset>
    }
    &#13;
    &#13;
    &#13;

    1. 创建一个控制器方法来处理局部视图

      public ActionResult CreateHighSchoolTypePartial()
      {
          return PartialView();
      }
      
      [HttpPost]
      public ActionResult CreateHighSchoolTypePartial(LookupEditModel viewModel)
      {
          if (!ModelState.IsValid)
          {
              return PartialView(viewModel);
          }
      
          var hsType = (from t in _highSchoolTypeRepository.FindAll()
                        where t.Name == viewModel.Name
                        select t).FirstOrDefault();
      
          if (hsType != null)
          {
              ModelState.AddModelError("Name", String.Format("This high school type already exists.", viewModel.Name));
              return PartialView(viewModel);
          }
      
          _highSchoolTypeRepository.Save(new HighSchoolType
          {
              Name = viewModel.Name
          });
      
          return PartialView();
      }
      
    2. 使用一些jquery

    3. 连接所有内容

      对话框打开

      &#13;
      &#13;
          $("#AddHighSchoolTypeDialog").dialog({
              position: 'center',
              autoOpen: false,
              modal: true,
              resizable: false,
              draggable: false,
              title: "Add a new high school type",
              open: function (event, ui) {
                  //Load the CreateAlbumPartial action which will return 
                  // the partial view _CreateAlbumPartial
                  $(this).load("/HighSchoolType/CreateHighSchoolTypePartial", function () {
                      $("form#CreateHighSchoolTypeForm input:first").focus(); 
                  });
              },
              focus: function (event, ui) {
      
              },
              close: function (event, ui) {
                  $.ajax({
                      url: "/HighSchoolType/GetAllHighSchoolTypes",
                      type: "GET",
                      success: function (data) {
                          $("#HighSchoolTypeId option").remove();
                          $.each(data, function (key, value) {
                              $('#HighSchoolTypeId')
                                          .append($("<option></option>")
                                          .attr("value", key)
                                          .text(value));
                          });
                      }
                  });
                  //$("#AddHighSchoolTypeDialog").remove();
              },
              width: 600
          });
      &#13;
      &#13;
      &#13;

      和帖子

      &#13;
      &#13;
          $("#CreateHighSchoolTypeButton").live('click', function () {
              $.ajax({
                  url: "/HighSchoolType/CreateHighSchoolTypePartial",
                  type: "POST",
                  data: $("#CreateHighSchoolTypeForm").serialize(),
                  error: function (data) {
                      var errorMessage = $.parseJSON(data.responseText);
                  },
                  success: function (data) {
                      if (data) {
                          $('#AddHighSchoolTypeDialog').html(data);
                      }
                      else {
                          $('#AddHighSchoolTypeDialog').html('no data');
                      }
                  }
              });
      
              return false;
          });
      &#13;
      &#13;
      &#13;

      请注意成功后需要将模态的html替换为post调用返回的内容。

答案 1 :(得分:0)

根据我的理解,您正在尝试在一个页面中创建多个表单。你可以试试这样的东西 -

     @using (Html.BeginForm("Login", "Member", FormMethod.Post, new {})) {

        @Html.LabelFor(m => m.LoginUsername)
        @Html.TextBoxFor(m => m.LoginUsername)

        @Html.LabelFor(m => m.LoginPassword)
        @Html.TextBoxFor(m => m.LoginPassword)

        <input type='Submit' value='Login' />

    }

    @using (Html.BeginForm("Register", "Member", FormMethod.Post, new {})) {

        @Html.LabelFor(m => m.RegisterFirstName)
        @Html.TextBoxFor(m => m.RegisterFirstName)

        @Html.LabelFor(m => m.RegisterLastName)
        @Html.TextBoxFor(m => m.RegisterLastName)

        @Html.LabelFor(m => m.RegisterUsername)
        @Html.TextBoxFor(m => m.RegisterUsername)

        @Html.LabelFor(m => m.RegisterPassword)
        @Html.TextBoxFor(m => m.RegisterPassword)

        <input type='Submit' value='Register' />
}

在一个页面内。

您可以在此链接上查看答案 - asp.net MVC 4 multiple post via different forms

答案 2 :(得分:0)

不显眼的验证仅适用于页面加载时存在的表单。如果要在模态中加载动态页面,则需要在加载后注册它们

$.validator.unobtrusive.parse("#formid")

或者您可以隐藏加载时的视图并在需要时显示

相关问题