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

2

13

I have the following DropDownList in an ASP.NET MVC cshtml page:

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

The property is defined as public virtual Nullable<int> GroupId

Although GroupId is Nullable the select menu won't accept an empty option. If I try to save the model without selecting a group, I get the following error message:

The field GroupId must be a number.

The select menu is being rendered like this:

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

And no, GroupId is not decorated with the [Required] attribute.

How can I make it so the page will accept an empty value for the GroupId?

P.S. The GroupId type (Nullable<int>) is code-generated. I use the database-first scheme. I don't know though what is the difference between <Nullable>int and int?

UPDATE:

Even having zero as value for the empty select item does not pass the non-obstrusive (JavaScript) validation. However, putting a value of -1 passes both the client side and the server side validation. So for now, I am using this value and in the controller, I set GroupId to null if it equal to -1.

I cannot believe there no simpler solution to such a simple problem. Is this is a bug in ASP.NET MVC 3?

Protecting answered 4/3, 2014 at 21:23 Comment(1)
Is GroupId decorated with any other attribute?Chancre
S
0

Create Class for Model Bind

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

Create Controller

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

Index.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> 
}
Stacee answered 25/4, 2016 at 6:27 Comment(0)
B
0

Try this to display blank values in drop down list

Model

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

Controller

    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");

View

@Html.DropDownList("products",@ViewBag.products as List<SelectListItems>)
Bohlen answered 4/12, 2020 at 1:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.