asp.net-mvc MVC 中下拉列表的验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19299459/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 03:12:19  来源:igfitidea点击:

Validation for dropdown list in MVC

asp.net-mvcvalidationrazor

提问by Ajay

I am new to MVC and I am still trying to explore stuffs inside MVC. Now I came to place where I need to implement validation for drop-down list.

我是 MVC 的新手,我仍在尝试探索 MVC 内部的东西。现在我来到了需要对下拉列表进行验证的地方。

I spent fair amount of time searching for validation in MVC. But I dint get any result which suits to my problem. Please bear in mind that I am new to MVC so correct me if I my approach is wrong for implementing validation.

我花了相当多的时间在 MVC 中搜索验证。但我无法得到任何适合我的问题的结果。请记住,我是 MVC 的新手,所以如果我的方法在实现验证方面是错误的,请纠正我。

I created model class like this :

我创建了这样的模型类:

public class ValidationModel
{
    [Required(ErrorMessage = "Please select atleast one option")]
    public string dropdown { get; set; }
}

And In my controller I am using this code :

在我的控制器中,我使用了以下代码:

@using (Html.BeginForm("selectIndex", "Home", FormMethod.Post))
{
    <select name ="dropdwnMode" id="dropdwnMode" class="textbox">
        <option selected="selected" value="">Select Mode 
        @Html.ValidationMessageFor(Model => Model.dropdown) </option>
        <option value="1"> Add or Update Customer </option>
        <option value="2">Update Customer Credit</option>
     </select>
}

Here what I want is when my drop-down list is in Select Modethat is default, it should show please select at least one optionerror and if user selects 1st or 2nd option then this error message should not display.

这里我想要的是当我的下拉列表处于默认选择模式时,它应该显示请至少选择一个选项错误,如果用户选择第一个或第二个选项,则不应显示此错误消息。

But Now it is not displaying any message if I use above approach. So can someone guide me in achieving this?

但是现在如果我使用上述方法,它不会显示任何消息。那么有人可以指导我实现这一目标吗?

回答by mayabelle

I would recommend replacing your "Dropdown" property on the model with two properties - one that would hold the selected value and one that would hold all possible values. Then you can use an HTML helper (Razor syntax) to create your dropdown in the view, and MVC would take care of the validation.

我建议用两个属性替换模型上的“下拉”属性 - 一个保存选定的值,一个保存所有可能的值。然后您可以使用 HTML 帮助程序(Razor 语法)在视图中创建下拉列表,MVC 将负责验证。

Model:

模型:

public class ValidationModel
{
    /// <summary>
    ///     ID of the selected option
    /// </summary>
    [Required(ErrorMessage = "Please select at least one option")]
    public int SelectedOptionID { get; set; }

    /// <summary>
    ///     Possible values for the dropdown
    /// </summary>
    public IEnumerable<OptionModel> Options { get; set; }
}

OptionModel:

选项模型:

public class OptionModel
{
    /// <summary>
    ///     ID (key that uniquely identifies this option)
    /// </summary>
    public int ID { get; set; }

    /// <summary>
    ///     Name (value or display text that will be shown in the UI)
    /// </summary>
    public string Name { get; set; }
}

You could also store other properties on the option model if needed. Alternatively, you could use a key-value-pair or dictionary instead of the option model to avoid creating a class, which would be faster but less clear.

如果需要,您还可以在选项模型上存储其他属性。或者,您可以使用键值对或字典而不是选项模型来避免创建类,这会更快但不太清楚。

View:

看法:

@model ValidationModel

@using (Html.BeginForm("selectIndex", "Home", FormMethod.Post))
{
    @Html.ValidationMessageFor(Model => Model.SelectedOptionID)

    @Html.DropDownListFor(m => m.SelectedOptionID,
        new SelectList(Model.Options, "ID", "Name"),
        "Select an option") // Default text before the user has selected an option
}

You could name Options and SelectedOptionID a bit better to clarify their usage depending on your implementation.

您可以根据您的实现更好地命名 Options 和 SelectedOptionID 以阐明它们的用法。

With this implementation you would (and should) populate the options list from your controller. The selected option would be populated when the user selects an option. Like this:

使用此实现,您将(并且应该)从控制器填充选项列表。当用户选择一个选项时,将填充选定的选项。像这样:

Controller:

控制器:

public ActionResult YourAction()
{
    ValidationModel model = new ValidationModel();
    model.Options = new List<OptionModel> {
        new OptionModel { ID = 1, Value = "Add or Update Customer" },
        new OptionModel { ID = 2, Value = "Update Customer Credit" }
    }

    return View("YourViewName", model);
}

As a side note, I would recommend naming your ValidationModel after what the view that uses it is doing (e.g. HomepageModel if your view is the entire homepage or NavigationFormModel if your view is just a partial view that contains a dropdown for navigation).

作为旁注,我建议您以使用它的视图正在执行的操作命名您的 ValidationModel(例如 HomepageModel,如果您的视图是整个主页,或者 NavigationFormModel,如果您的视图只是包含导航下拉列表的部分视图)。