Wednesday 20 September 2017

Adding SelectListItem manually to SelectList to use in DropDownListFor

Use DropDownList and name it the same as the model's property name. Mine is "ItemType"
     @Html.LabelFor(model => model.ItemType, new { @class = "control-label" })
     @Html.DropDownList("ItemType", (IEnumerable<SelectListItem>)ViewBag.ItemTypes, new { @class = "form-control" })
     @Html.ValidationMessageFor(model => model.ItemType, null, new { @class = "text-danger" })

        var types = new List<SelectListItem>();
        types.Add(new SelectListItem() { Text = "Select...", Value = string.Empty });
        types.Add(new SelectListItem() { Text = "OTC", Value = "0" });
        types.Add(new SelectListItem() { Text = "Generic", Value = "1" });
        types.Add(new SelectListItem() { Text = "Brand", Value = "2" });
        types.Add(new SelectListItem() { Text = "Non-Merchandise", Value = "9" });

        ViewBag.ItemTypes = types;

    [Required(ErrorMessage = "Item Type is required")]
    public Int32 ItemType { get; set; }

No comments:

Post a Comment

Note: only a member of this blog may post a comment.

Blog Archive