简体   繁体   English

客户端验证 <select>在asp.net MVC 4中

[英]client side validation of <select> in asp.net MVC 4

I am working on asp.net MVC application. 我正在研究asp.net MVC应用程序。 I have a dropdown like this in my razor view: 我的剃须刀视图中有这样的下拉列表:

 <select id="ddlAreaID">
 @foreach (var item in Model.Areas)
 {
     <optgroup label="@item.CityName">
     @foreach (var val in item.Areas)
     {
         var selected = (val.AreaID == Model.AreaID) ? "selected=selected" : string.Empty;
         <option value="@val.AreaID" @selected>@val.AreaName</option>
     }
     </optgroup>
 }
 </select>
 @Html.HiddenFor(m => m.AreaID)

I have added first item to collection like this: 我已将第一个项目添加到集合中,如下所示:

Areas.Insert(0, new CityInfo() 
{
    Areas = new List<AreaInfo>() 
    { 
        new AreaInfo() 
        { 
            AreaID = 0, 
            AreaName = "select an Area" , 
            CityName = "" 
        }
    }  
});

I want to perform client validation of this select/drop down so that at least one item is selected. 我想对此选择/下拉菜单执行客户端验证,以便至少选择一个项目。 How can I do this ? 我怎样才能做到这一点 ?

Please suggest. 请建议。

You should start refactoring your view model and your view. 您应该开始重构视图模型和视图。 Your current design is pretty static and has some coupling issues. 您当前的设计非常静态,并且存在一些耦合问题。 For example it already looks wrong to create an area, named "Select an area!". 例如,创建一个名为“选择区域!”的区域已经看错了。

I don't know how your view model is named, but for example concerncs, I will call it ViewModel . 我不知道您的视图模型是如何命名的,但是例如关注软件,我将其称为ViewModel The view model represents the data of the view. 视图模型表示视图的数据。 So in your use case, you wish to select an area. 因此,在您的用例中,您希望选择一个区域。 There is a predefined set of areas you give the view to render the drop-down. 您可以为视图提供一组预定义的区域来呈现下拉列表。 And you wish to get back the user selection. 并且您希望取回用户选择。 Therefor you will end with two properties, representing this data: 因此,您将以两个属性结束,表示此数据:

public class ViewModel
{
    public List<AreaModel> AvailableAreas { get; set; }

    public AreaModel SelectedArea { get; set; }
}

Since AvailableAreas is required to build up the view, you can define a constructor that accepts a list of areas to initialize the property. 由于构建视图需要AvailableAreas ,因此您可以定义一个构造函数,该构造函数接受要初始化属性的区域列表。 However, this is not mandatory. 但是,这不是强制性的。

In your view you can now use helpers to make generate your drop down list: 在您的视图中,您现在可以使用帮助程序生成下拉列表:

@Html.DropDownListFor(m => m.SelectedArea, Model.AvailableAreas, "Select an area")

This really simplifies your view! 这真的简化了你的观点! And now you can also use data annotations to enable client-side validation: 现在您还可以使用数据注释来启用客户端验证:

public class ViewModel
{
    public List<AreaModel> AvailableAreas { get; set; }

    [Required]
    public AreaModel SelectedArea { get; set; }
}

This should get you into the right direction. 这应该让你走向正确的方向。 However, I still see some problems with your option groups. 但是,我仍然看到您的选项组存在一些问题。 If you are forced to use them, here is something to read on: Consuming a Helper code for optgroup functionality in Asp.net MVC . 如果您被迫使用它们,请阅读以下内容: 在Asp.net MVC中为optgroup功能使用Helper代码

You could use jQuery to validate that the selected index is greater than 0 before submitting the form. 在提交表单之前,您可以使用jQuery验证所选索引是否大于0。 Something like 就像是

$("form").submit(function(){
     if($("#ddlAreaID")[0].selectedIndex === 0) {
         // display error message
         return false;
     }
     return true; 
});
so that at least one item is selected

Looking at your dropdownlist, it's not a multiple select. 查看您的下拉列表,它不是多选。 Any dropdownlist (that has options inside it) always has a value selected (unless specified, it selects the first element by default). 任何下拉列表(其中都有选项)总是选择一个值(除非指定,否则默认选择第一个元素)。

Also, it can't have more than one value selected (since it's not a multiple select). 此外,它不能选择多个值(因为它不是多选)。

In your code snippet, I don't see you adding a dummy either (eg an option labeled "Please select one option"). 在您的代码段中,我没有看到您添加虚拟(例如标记为“请选择一个选项”的选项)。

If I take your question to the letter, you don't need any validation. 如果我把问题提到信中,你就不需要任何验证。

Now I'm going to assume that a dummy option will be added, and you want to validate that the user has selected any option except the dummy . 现在我将假设将添加一个虚拟选项,并且您要验证用户是否已选择除虚拟选项之外的任何选项。

First: add the dummy. 第一:添加假人。

<select id="ddlAreaID">

    <!-- This is the dummy. Note that its value is "dummy" -->
    <option value="dummy">Please select an area...</option>

 @foreach (var item in Model.Areas)
 {
     <optgroup label="@item.CityName">
     @foreach (var val in item.Areas)
     {
         var selected = (val.AreaID == Model.AreaID) ? "selected=selected" : string.Empty;
         <option value="@val.AreaID" @selected>@val.AreaName</option>
     }
     </optgroup>
 }
</select>

Your selectlist (presumably) gets posted back via a form. 您的选择列表(可能)通过表单发回。 So what you'll want to do is: 所以你想要做的是:

  • When the form is submitted, catch it before it submits. 提交表单时,请在提交表单之前将其捕获。
  • Check that the dummy wasn't selected 检查未选择假人
  • If everything is okay, the form can be submitted. 如果一切正常,可以提交表格。
  • If validation fails, do not submit the form. 如果验证失败,请不要提交表单。

I'm assuming your form has an id ( #myForm , by way of example). 我假设你的表单有一个id( #myForm ,举个例子)。

$("#myForm").submit( function (event) {

    //The form has not yet submitted, and it is waiting for this function to complete.

    if( $("#ddlAreaID").val() === "dummy" ) //this needs to match the value you gave the dummy option
    {
        alert("You did not choose an area!");

        event.preventDefault(); //this line makes sure the form does not get submitted.
    }

    //If everything is still okay, we can simply exit the function. Form submission will continue.
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM