Ok dokey, I have the following set up.
Model
public class SupplyType
{
[Key]
public int SupplyTypeId { get; set; }
public string SupplyTypeName { get; set; }
}
public class Supply
{
[Display(Name = "What type of supply is this from?")]
public int SupplyTypeId { get; set; }
public IEnumerable<SupplyType> SupplyType { get; set; }
}
Controller
public ActionResult (Guid id)
{
var model = Model(id);
model.Supply.SupplyType = db.SupplyTypes.ToList();
return View(model.);
}
I now have a View of the following
//Good view
<div class="editor-label">
@Html.LabelFor(model => model.SupplyTypeId, "SupplyType")
</div>
<div class="editor-field">
@Html.DropDownListFor(x => x.SupplyTypeId, new SelectList(Model.SupplyType, "SupplyTypeId", "SupplyTypeName"))
@Html.ValidationMessageFor(model => model.SupplyTypeId)
</div>
This works fine and dandy, if I don’t pass touch it, then validation does not fire and I can click on post buttons on my page.
However, when I try and implement a ” — Please Select — ” item in the list, the validation strikes and I’m stuck, can’t click on one of my post buttons..boo!!
//Bad view
<div class="editor-label">
@Html.LabelFor(model => model.SupplyTypeId, "SupplyType")
</div>
<div class="editor-field">
@Html.DropDownListFor(x => x.SupplyTypeId, new SelectList(Model.SupplyType, "SupplyTypeId", "SupplyTypeName"), " -- Please Select -- ")
@Html.ValidationMessageFor(model => model.SupplyTypeId)
</div>
I still require a ” — Please Select — ” item in the drop down but I don’t want the validation to strike if this hasn’t been set.
Any ideas of how I can get around this without turning validation off completely? The reason for this is that the drop down lists will be conditionally shown and therefore might not need to be populated.
Any help greatly received.
For your specific requirement like this, I think the simple way is to add
-- Please Select --as a newList ItemwithSupplyTypIDvalue as0.