必需的验证不适用于MVC中的DropdownList

时间:2017-04-28 07:24:03

标签: asp.net asp.net-mvc

enter image description here

    Below View Code. when i click on  Create button without  Selecting  Activity. it is not showing validation message. i am using Required attribute in Model Class

        <div class="form-group">
           @Html.LabelFor(model => model.TransactionTypeID, htmlAttributes: new { @class = "control-label col-md-2" })
           <div class="col-md-10">
             @Html.DropDownListFor(model => model.TransactionTypeID, new SelectList(ViewBag.GetT, "TransactionTypeID", "TransactionType"), "--Select--", new { htmlAttributes = new { @class = "form-control" } })
             @Html.ValidationMessageFor(model => model.TransactionTypeID, "", new { @class = "text-danger" })
           </div>
        </div>

        <div class="form-group">
        @Html.LabelFor(model => model.ActivityID, htmlAttributes: new { @class = "control-label col-md-2" })
          <div class="col-md-10">
            @Html.DropDownListFor(model => model.ActivityID, new SelectList(ViewBag.GetA, "ActivityID", "ActivityName"), "--Select--", new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.ActivityID, "", new { @class = "text-danger" })
          </div>
        </div>


//Controller code
  public ActionResult Create()
        {
            List<TransactionTypeMaster> T = new DATransactionTypeMaster().GetListAll();
            ViewBag.GetT = T;

            List<ActivityMaster> A = new DAActivityMaster().GetListAll();
            ViewBag.GetA = A;

            return View();
        }

可以为此提供任何帮助。需要知道我哪里错了 当我单击“创建”按钮而不选择“活动”时。它没有显示验证消息。我在模型类

中使用Required属性

2 个答案:

答案 0 :(得分:1)

尝试在下拉菜单中为默认的'--Select--'选项提供值0。

在您的模型中,请确保您的下拉值设置为“[必需]”,并为其指定属性:

[Range(1, Int32.MaxValue, ErrorMessage = "Must Select A Value")]

基本上只让它接受值&gt; 0

答案 1 :(得分:0)

我认为你的TransactionTypeID是int,使那个可以解决这个问题的Nullable。目前它不起作用,因为默认情况下它可能使用null作为值发送零,当用户不接触此字段时它将发送null。