【问题标题】:values populated using jquery lost on server side validation mvc4使用 jquery 填充的值在服务器端验证 mvc4 上丢失
【发布时间】:2014-04-16 08:49:48
【问题描述】:

查看

@Html.DropDownListFor(model => model.PracticGropupId, new SelectList(Model.PracticeGroup, "Value", "Text"))
@Html.DropDownListFor(model => model.SubPracticeGroupId, Enumerable.Empty<SelectListItem>(), new { style = "width:250px;" })

JS

$('#PracticGropupId').change(function () {

    var selectedGroupId = $(this).val();

    $.getJSON('/Business/SubPracticeGroup', { practiceGroup: selectedGroupId }, function (subGroups) {
        var subGroupsSelect = $('#SubPracticeGroupId');
        subGroupsSelect.empty();
        subGroupsSelect.append(
                $('<option/>')
                    .attr('value', '')
                    .text('Subgroup')
            );
        $.each(subGroups, function (index, subGroup) {
            subGroupsSelect.append(
                $('<option/>')
                    .attr('value', subGroup.Code)
                    .text(subGroup.Name)
            );
        });
    });
});

如果服务器端验证失败,则提交时出现错误消息,并且 SubPracticeGroupId 下拉列表中的值变为空白。这也发生在我使用 jQuery ajax 动态生成的 HTML 上。有没有办法在服务器端验证后保留这些值?

【问题讨论】:

  • 这是因为您将绑定的选定值发送回ActionResult 而不是列表,因为列表没有绑定到任何东西。
  • 你应该使用 Ajax.BeginForm 而不是 Html.BeginForm
  • @ehsan Sajjad 使用 Ajax.BeginForm 会保留该值,但会丢失所有错误消息。我应该怎么做才能显示错误消息。
  • 你在谈论验证消息??
  • 是的,我说的是验证消息。

标签: jquery validation asp.net-mvc-4


【解决方案1】:

使用 Ajax.BeginForm 而不是 Html.BeginForm,因为 Html.BeginForm 将执行完整的回发,您将无法保留它们,通过使用 Ajax.BeginForm 数据将被异步发布。

【讨论】:

    【解决方案2】:

    我就是这样做的。我按照 Html.Begin 形式更改了

    @using (Html.BeginForm("ActionName", "ControllerNmae", FormMethod.Post, new { enctype = "multipart/form-data" }))
    

    @using (Ajax.BeginForm("ActionName", "ControllerNmae", new AjaxOptions
    {
        InsertionMode = InsertionMode.InsertAfter, 
        HttpMethod = "POST",
        OnFailure = "ShowFailureMessage",
        OnSuccess="Success",
        UpdateTargetId ="error",
    }))
    

    为了显示验证消息,我创建了一个局部视图并将其绑定到与我的父视图相同的 ViewModel。 _error.cshtml

        @model Project.ViewModels.VieModelName
    
       <div class="error" >
           @Html.ValidationSummary(false)
        </div>
    

    在父视图中添加了 div 以显示验证消息。该 div 的 ID 将与 ajax 参数 Parentview.cshtml 中定义的相同

    <div class="error" id="error" >
         @Html.ValidationSummary(false)
         @Html.Partial("_error")
     </div>
    

    最后在控制器中:

      if (ModelState.IsValid)
      {
         .. Save logic
      }
      else
      {
         return PartialView("_error", VieModelName);
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-15
      • 2011-11-11
      • 2010-12-28
      • 1970-01-01
      • 1970-01-01
      • 2013-09-06
      相关资源
      最近更新 更多