验证不适用于动态@ Html.DropDownListFor

时间:2015-09-08 15:17:52

标签: c# jquery asp.net-mvc

我有一个departmentID的下拉列表,根据DepartmentCategoryID中选择的内容填充,但是我可以;如果它保持为空,则验证是否有效。它是有效的或所有其他的,但这是以不同的方式完成的。

<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中设置,但这也不起作用 - 不确定隐藏的是否可以缺少验证?

<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中的标记填充了列表并且是来自视图包吗?

有人有解决方案吗?

1 个答案:

答案 0 :(得分:4)

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

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

,其值为0,对typeof int有效,因此永远不会出现验证错误。将其更改为

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

此外,您手动为第二个<select>元素

创建html
<select id="txtDepartment" name="txtDepartmentID"></select>

,其名称属性与您的模型无关。相反,使用

强烈绑定到您的模型
@Html.DropDownListFor(m => m.DepartmentID, Enumerable.Empty<SelectListItem>())

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

附注:

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

    [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);
    }
    
相关问题