【问题标题】:Validation not working on dynamic @Html.DropDownListFor验证不适用于动态 @Html.DropDownListFor
【发布时间】:2015-09-08 15:17:52
【问题描述】:

我有一个根据 DepartmentCategoryID 中选择的内容填充的部门 ID 下拉列表,但是如果它留空,我无法进行验证。它可以工作或其他所有工作,但这样做的方式不同。

<div style="display: table-row;">
  <div class="div-label-text-mandatory" , style="display: table-cell">
    @Html.LabelFor(model => model.DepartmentCategoryID)
  </div>
  <div class="div-dropdown-menu" , style="display: table-cell">
    @Html.DropDownListFor(model => model.DepartmentCategoryID (SelectList)ViewBag.DepartmentCategory, "Please select a Staff category", new { @id = "txtDepCatID", @onchange = "javascript:GetCity(this.value);" })
  </div>
  <div class="div-val-cell" , style="display: table-cell">
    @Html.ValidationMessageFor(model => model.DepartmentCategoryID, "", new { @class = "text-danger" })
  </div>
</div>              

<div id="DepartmentDiv" style="display: none;">
  <div class="div-label-text-mandatory" , style="display: table-cell"></div>
  <div class="div-dropdown-menu" , style="display: table-cell">
    @Html.LabelFor(model => model.DepartmentID): 
    <select id="txtDepartment" name="txtDepartmentID"></select>
  </div>
  <div class="div-val-cell" , style="display: table-cell">
    @Html.ValidationMessageFor(model => model.DepartmentID, "", new { @class = "text-danger" })
  </div>
</div>

我尝试添加一个隐藏的部分,我将在 jquery 中设置,但这也不起作用 - 不确定 hidden for 是否会丢失验证?

<div style="display: table-row;">
  <div class="div-label-text-mandatory" , style="display: table-cell"></div>
    <div class="div-dropdown-menu" , style="display: table-cell">
      @Html.HiddenFor(model => model.DepartmentID)
    </div>
    <div class="div-val-cell" , style="display: table-cell">
      @Html.ValidationMessageFor(model => model.DepartmentID, "", new { @class = "text-danger" })
    </div>
</div>  

Jquery 填充列表:

<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script language="javascript" type="text/javascript">
    function GetCity(_GetSubDepartment) {
        var procemessage = "<option value='0'> Please wait...</option>";
        $("#txtDepartment").html(procemessage).show();
        var url = "@Url.Content("~/Employee/_GetSubDepartment")";

        $.ajax({
            url: url,
            data: { DepartmentCategoryID: _GetSubDepartment },
            cache: false,
            type: "POST",
            success: function (data) {
                console.log("Data length: "+data.length)
                if ((data.length) == 0) {
                    $('#DepartmentDiv').hide();
                }
                if ((data.length) > 0) {
                    var markup = "<option value='0'>Select department</option>";
                    for (var x = 0; x < data.length; x++) {
                        markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
                        $("#txtDepartment").html(markup).show();
                        //$('#DepartmentDiv').css('display', 'table-row').animate("slow");
                        $('#DepartmentDiv').css('display', 'table-row').show();
                    }

                }
            },
            error: function (reponse) {
                alert("error : " + reponse);

            }
        });

    }
</script>

型号

[DisplayName("Staff category")]
[Required(AllowEmptyStrings = false, ErrorMessage = " * is mandatory")]
public int DepartmentCategoryID { get; set; }

[DisplayName("Departments")]
[Required(AllowEmptyStrings = false, ErrorMessage = " * is mandatory")]
public int DepartmentID { get; set; }

控制器:

[HttpPost]
public ActionResult _GetSubDepartment(int? DepartmentCategoryID)
{
    ViewBag.Department = new SelectList(db.vwDimDepartments.Where(m => m.DepartmentCategoryID == DepartmentCategoryID).ToList(), "DepartmentID", "DepartmentName");

    return Json(ViewBag.Department);
}

这是因为 Jquery 中的标记填充列表并且它来自视图包吗?

有人对此有解决方案吗?

【问题讨论】:

标签: c# jquery asp.net-mvc


【解决方案1】:

您将第二个下拉列表中的第一个选项添加为

var markup = "<option value='0'>Select department</option>";

它的值为0,它对typeof int 有效,因此永远不会出现验证错误。改成

var markup = "<option value=''>Select department</option>";

此外,您还为第二个 &lt;select&gt; 元素手动创建 html

<select id="txtDepartment" name="txtDepartmentID"></select>

具有与您的模型无关的名称属性。相反,使用强绑定到您的模型

@Html.DropDownListFor(m => m.DepartmentID, Enumerable.Empty<SelectListItem>())

并调整您的脚本,使其引用$('#DepartmentID')(而不是$('#txtDepartment')

旁注:

  1. AllowEmptyStrings = falseint 类型毫无意义(及其 无论如何都是默认的)所以你可以删除它。
  2. 您的 _GetSubDepartment() 方法不应返回 SelectList(你只是返回了不必要的额外数据 降低性能。

应该是

[HttpGet] // Its a get,  not a post (change the ajax option)
public ActionResult _GetSubDepartment(int? DepartmentCategoryID) // The parameter should be int (not nullable) or test for null
{
  var data = db.vwDimDepartments.Where(m => m.DepartmentCategoryID == DepartmentCategoryID).Select(d => new
  {
    Value = d.DepartmentID,
    Text = d.DepartmentName
  };
  return Json(data, JsonRequestBehavior.AllowGet);
}

【讨论】:

  • 感谢您的信息,但如果未选择验证消息,我仍然没有收到验证消息。这是因为我在剃须刀的模型字段中没有任何输入选项吗?正在填充下拉列表,但它并没有真正分配给剃刀中的 model.DepartmentID,以便它知道我猜它需要验证。我为该字段创建了一个文本框,显示为无,但验证在此之外,但仍然不起作用,猜测显示无也覆盖了验证。
  • 不,您的问题是您使用&lt;select id="txtDepartment" name="txtDepartmentID"&gt;&lt;/select&gt; 手动创建了控件-您的模型没有名为txtDepartmentID 的属性。使用@Html.DropDownListFor(m =&gt; m.DepartmentID, Enumerable.Empty&lt;SelectListItem&gt;()
  • 太好了,谢谢!完美运行。非常感谢您的帮助。
猜你喜欢
  • 2015-03-05
  • 1970-01-01
  • 2023-03-08
  • 1970-01-01
  • 2016-08-21
  • 1970-01-01
  • 2016-09-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多