如何使用所需的验证创建ASP.Net MVC DropDownList [英] How to create ASP.Net MVC DropDownList with required validation

查看:82
本文介绍了如何使用所需的验证创建ASP.Net MVC DropDownList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用mvc5.我正在使用ORM从数据库中加载数据,并从控制器中填充一个下拉列表,就像这样.

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

因为我首先想要一个空字段,所以我正在用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>

空选项的值为"0".

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

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

问题是,永远不会让我出错.始终为"0",并且没有进行验证.

我缺少什么?

解决方案

使用 DropDownList 的方法很少.我个人喜欢使用Strongly-Type ViewModel ,而不是 ViewBag .. >

屏幕截图

单击提交按钮但未选择国家/地区时,将显示验证消息.

实体

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

型号

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>();
    }
}

控制器

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;
    }
}

查看

@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>

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

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

As i wanted an empty field first I am doing this in my 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.

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.

What I a missing?

解决方案

There are few ways to work with DropDownList. I personally like to use Strongly-Type ViewModel instead of ViewBag.

Screen Shot

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

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>

这篇关于如何使用所需的验证创建ASP.Net MVC DropDownList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆