簡體   English   中英

asp.net mvc jquery下拉列表驗證

[英]asp.net mvc jquery dropdown validation

我如何用不引人注目的javascript驗證dropdownlist? 作為驗證所需驗證器的文本框,但它不適用於下拉列表?

需要為它改變不顯眼的js文件嗎? 或者還有其他選項來驗證下拉列表嗎?

我想在我的javascript中檢查form.validate()時顯示錯誤。

    $(function () {
        $("#form1").validate({
            rules: {
                ProductCategoryList: {
                    required: true
                }

            },
            messages: {
                ProductCategoryList: {
                    required: "This field is required"
                }
            }
        });
    });

您必須保留第一個選項value=""才能生效。

<asp:ListItem Value="">- Select Something -</asp:ListItem>

如果要集成驗證jQuery,則需要指定字段

使用DropDownListFor而不是DropDownList

@Html.DropDownListFor(c => c.Profile_Id, null, "-- Choose --", new { @class = "input-large" })

如果列表與字段具有相同的名稱,則不需要將ViewBag.Profile_Is as SelectList因為如果在列表中發送空值,則它不適用於編輯方案。

標記

 <p>
        <label for="ProductCategoryList">Product Categories</label>
        <%= Html.DropDownList("ProductCategoryList", ViewData["ProductCategories"] as SelectList)%>
    </p>

和驗證腳本

        $.validator.addMethod("selectNone",
            function (value, element) {
                return this.optional(element) || element.selectedIndex != 0;
            },
           "Please select an option."
        );


        $(function () {
            $("#form1").validate({
                rules: {
                    ProductCategoryList: {
                        selectNone: true
                    }

                },
                messages: {
                    ProductCategoryList: {
                        selectNone: "This field is required"
                    }
                }
            });
        });

我通過在Viewmodel上創建一個屬性來實現這個功能,該屬性用於綁定DropDownList中的selecteditem。 一個例子會說清楚:

視圖中的代碼:

        <div class="editor-field">
           @Html.DropDownListFor(model => model.SelectedPlantID,
                                 new SelectList(Model.Plants, "Value", "Text"),
                                 " ", new { id = "ddlPlant" })

          @Html.ValidationMessageFor(model => model.SelectedPlantID)
    </div>

ViewModel中的代碼將(強烈鍵入視圖):

            private List<SelectListItem> _plants = new List<SelectListItem>();
    [Required]
    [Display(Name = "Plant")]
    public List<SelectListItem> Plants
    {
        get
        {
            return (_plants);
        }

        set
        {
            _plants = value;
        }
    }

    public Guid SelectedPlantID
    {
        get;
        set;
    }

注意:SelectedPlantID不必是模型上的字段。

希望這對你有用!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM