如何使绑定到 Nullable<int> 属性的 DropDownListFor 接受空值?

How to make a DropDownListFor bound to a Nullable<int> property accept an empty value?

提问人:Jean-François Beauchamp 提问时间:3/5/2014 最后编辑:Vadim OvchinnikovJean-François Beauchamp 更新时间:12/4/2020 访问量:3685

问:

我在 ASP.NET MVC cshtml 页面中有以下 DropDownList:

@Html.DropDownListFor(model => model.GroupId, (IEnumerable<SelectListItem>)ViewBag.PossibleGroups, "")

该属性定义为public virtual Nullable<int> GroupId

虽然菜单不会接受空选项。如果我尝试在不选择组的情况下保存模型,我会收到以下错误消息:GroupIdNullableselect

该字段必须是数字。GroupId

选择菜单的呈现方式如下:

<select data-val="true" data-val-number="The field GroupId must be a number." id="GroupId" name="GroupId" class="input-validation-error" data-hasqtip="0" aria-describedby="qtip-0">
    <option value=""></option>
    <option value="1">Test Group</option>
</select>

不,没有用属性装饰。GroupId[Required]

我怎样才能使页面接受一个空值?GroupId

P.S. 类型()是代码生成的。我使用数据库优先方案。我不知道 和 之间有什么区别?GroupIdNullable<int><Nullable>intint

更新

即使将空选择项的值设置为零,也不会通过非侵入性 (JavaScript) 验证。但是,将值 放入 会通过客户端和服务器端验证。所以现在,我正在使用这个值,在控制器中,我设置为如果它等于 .-1GroupIdnull-1

我不敢相信没有更简单的解决方案来解决这么简单的问题。这是 ASP.NET MVC 3 中的错误吗?

C# ASP.NET-MVC-3 验证 下拉菜单 可为空

评论

0赞 Pedro Drewanz 3/15/2016
GroupId 是否使用任何其他属性进行修饰?

答:

0赞 Kinfo 4/25/2016 #1

为模型绑定创建类

 public class BindDropDown
{
    public Nullable<int> ID{ get; set; }
    [Required(ErrorMessage = "Enter name")]
    public string Name{ get; set; } 
}

创建控制器

    namespace DropDown.Controllers
  {
public class HomeController : Controller
{
    public ActionResult Index()
    {
        ViewBag.Message = "Welcome to ASP.NET MVC!";

        ViewBag.InterviewList = NumberList;

        return View(new BindDropDown());
    }
    [HttpPost]
    public ActionResult Index(BindDropDown d)
    {
        if (ModelState.IsValid)
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";
        }
        else
        {
            ViewBag.Message = "error";
        }
        ViewBag.NumberList = NumberList;

        return View(new BindDropDown());
    }

    public ActionResult About()
    {
        return View();
    }

    public static IEnumerable<SelectListItem> NumberList
    {
        get
        {
            IEnumerable<NumberClass> interviewAppeals = Enum.GetValues(typeof(NumberClass))
                                                  .Cast<NumberClass>();
            return from item in interviewAppeals
                   select new SelectListItem
                   {
                       Text = item.ToString(),
                       Value = ((int)item).ToString()
                   };

        }
    }

}
public enum NumberClass
{
    One = 1,
    Two = 2,
    Three = 3
}
 }

索引.cshtml

@using DropDown.Models
@model BindDropDown
@{
ViewBag.Title = "Home Page";
 }

<h2>@ViewBag.Message</h2>
<p>

</p>
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { id =   "frmOnline" }))
{

@Html.ValidationSummary(false)   


<div class="w100">
    <div class="fleft">
        <label>ID :</label>
    </div>
    <div class="fleft">
        @Html.DropDownListFor(model => model.ID, (IEnumerable<SelectListItem>)ViewBag.NumberList, "")

    </div>
</div> 
<div class="w100">
    <div class="fleft">
        <label>Name :</label>
    </div>
    <div class="fleft">
        @Html.TextBoxFor(model => model.Name)
        @Html.ValidationMessageFor(model => model.Name)

    </div>
</div> 
<div class="w100 clear">
    <label>&nbsp;</label>
    <div class="fleft">
        <input type="submit" value="Save" class="button green" />
        @Html.ActionLink("Back", "GetAllAction", null, new { @class = "button gray" })

    </div>
</div> 
}
0赞 SenthilRaja Dhesign 12/4/2020 #2

尝试在下拉列表中显示空白值

public class Products {
public int pid {get;set;}
public String sValue {get; set;}
}

控制器

    List<Products> lstProducts = new List<Products>()
    {
    new Products() {pid=0, sValue=""},
    new Products() {pid=1, sValue="One"},
    new Products() {pid=2, sValue="Two"}
    };

ViewBag.products = new SelectList(lstProducts, "pid", "sValue");

视图

@Html.DropDownList("products",@ViewBag.products as List<SelectListItems>)