asp.net-mvc 如何使用所需的验证创建 ASP.Net MVC DropDownList

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41512619/
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-07 23:35:02  来源:igfitidea点击:

How to create ASP.Net MVC DropDownList with required validation

asp.net-mvcvalidationhtml.dropdownlistfordatamodel

提问by Diego

I working with mvc 5. I am loading data from Database Using ORM and fill a drop down list from the controller, like this.

我使用 mvc 5。我正在使用 ORM 从数据库加载数据并从控制器填充下拉列表,就像这样。

ViewBag.Country_id = new SelectList(_db.Countries, "Country_id", "Description");

As i wanted an empty field first I am doing this in my HTML.

因为我首先想要一个空字段,所以我在我的 HTML 中这样做。

<div class="form-group">
    @Html.LabelFor(model => model.Countries, "Country", htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownList("Country_id", null, htmlAttributes: new { @class = "form-control" }, optionLabel: "Choose a Country")
        @Html.ValidationMessageFor(model => model.Country_id, "", new { @class = "text-danger" })
    </div>
</div>

The empty choice has a "0" value.

空选项具有“0”值。

And i wanted to validate the user choose a Country so I add this Validation

我想验证用户选择一个国家,所以我添加了这个验证

[Required,Range(1, int.MaxValue, ErrorMessage = "Error: Must Choose a Country")]
public int Country_id { get; set; }

The Problem is that never get me a Error. Always is "0" and the validation did not occur.

问题是永远不会让我出错。始终为“0”且未进行验证。

What I a missing?

我缺什么?

回答by Win

There are few ways to work with DropDownList. I personallylike to use Strongly-Type ViewModelinstead of ViewBag.

有几种方法可以使用DropDownList。我个人喜欢使用 Strongly-Type ViewModel而不是ViewBag

Screen Shot

截屏

Validation message displays when submit button is clicked without selecting Country.

单击提交按钮而不选择国家/地区时,将显示验证消息。

enter image description here

在此处输入图片说明

Entity

实体

public class Country
{
    public int Country_id { get; set; }
    public string Description { get; set; }
}

Model

模型

public class CountryViewModel
{
    [Display(Name = "Country")]
    [Required(ErrorMessage = "{0} is required.")]
    public int SelectedCountryId { get; set; }

    public IList<SelectListItem> AvailableCountries { get; set; }

    public CountryViewModel()
    {
        AvailableCountries = new List<SelectListItem>();
    }
}

Controller

控制器

public class HomeController : Controller
{
    public ActionResult Create()
    {
        var countries = GetCountries();
        var model = new CountryViewModel {AvailableCountries = countries};
        return View(model);
    }

    [HttpPost]
    public async Task<ActionResult> Create(CountryViewModel countryViewModel)
    {
        if (ModelState.IsValid)
        {
            int countryId = countryViewModel.SelectedCountryId;
            // Do something
        }
        // If we got this far, something failed. So, redisplay form
        countryViewModel.AvailableCountries = GetCountries();
        return View(countryViewModel);
    }

    public IList<SelectListItem> GetCountries()
    {
        // This comes from database.
        var _dbCountries = new List<Country>
        {
            new Country {Country_id = 1, Description = "USA"},
            new Country {Country_id = 2, Description = "UK"},
            new Country {Country_id = 3, Description = "Canada"},
        };
        var countries = _dbCountries
            .Select(x => new SelectListItem {Text = x.Description, Value = x.Country_id.ToString()})
            .ToList();
        countries.Insert(0, new SelectListItem {Text = "Choose a Country", Value = ""});
        return countries;
    }
}

View

看法

@model DemoMvc.Models.CountryViewModel
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Create</title>
</head>
<body>

    <h2>Create</h2>

    @using (Html.BeginForm())
    {
        <div class="form-group">
            @Html.LabelFor(model => model.SelectedCountryId, 
               new {@class = "control-label col-md-2"})
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.SelectedCountryId, 
                    Model.AvailableCountries, new {@class = "form-control"})
                @Html.ValidationMessageFor(model => model.SelectedCountryId, 
                     "", new {@class = "text-danger"})
            </div>
        </div>

        <input type="submit" value="Submit"/>
    }

</body>
</html>

回答by Diego

Firstly, you cannot get any client side validation using the overload of DropDownList()that you are using. You need to use a different name for the property your binding to and the SelectList. Change the controller code to (say)

首先,您无法使用DropDownList()正在使用的重载进行任何客户端验证。您需要为绑定到的属性和SelectList. 将控制器代码更改为(例如)

ViewBag.CountryList = new SelectList(_db.Countries, "Country_id", "Description");

and change the model property attribute to (delete the RangeAttribute)

并将模型属性属性更改为(删除RangeAttribute

 [Required(ErrorMessage = "Error: Must Choose a Country")]
 public int Country_id { get; set; }

Then in the view use an overload that generates a nulllabel option

然后在视图中使用生成null标签选项的重载

@Html.DropDownListFor(m => m.Country_id, (SelectList)ViewBag.CountryList, "Choose a Country", new { @class = "form-control" })

If the user submits the form with the first ("Choose a Country") option selected, a validation error will be displayed.

如果用户提交表单时选择了第一个(“选择国家”)选项,则会显示验证错误。

Side note: It is recommended that you use a view model with a property public IEnumerable<SelectListItem> CountryList { get; set; }rather than ViewBag(and the view becomes @Html.DropDownListFor(m => m.Country_id, Model.CountryList, "Choose a Country", new { @class = "form-control" })

旁注:建议您使用带有属性的视图模型public IEnumerable<SelectListItem> CountryList { get; set; }而不是ViewBag(并且视图变为@Html.DropDownListFor(m => m.Country_id, Model.CountryList, "Choose a Country", new { @class = "form-control" })

回答by Hafsal Rh

Model Class

模型类

        [Display(Name = "Program")]
        [Required, Range(1, int.MaxValue, ErrorMessage = "Select Program")]
        public string Programid { get; set; 

View

看法

        @Html.DropDownListFor(Model=>Model.Programid,(IEnumerable<SelectListItem>)ViewBag.Program, new {@id = "ddlProgram"})

回答by Tom Stickel

For .net coreinstead of @Html.ValidationMessageFor(...

对于.net 核心而不是@Html.ValidationMessageFor(...

Use

razor cshtml

剃须刀 cshtml

<span asp-validation-for="SelectedCountryId" class="text-danger"></span>

model poco

模型 poco

[Required(ErrorMessage = "Country is required.")]
public int SelectedCountryId { get; set; }