I am building an ASP.Net MVC 3 Web application using Entity Framework 4.1. To perform validation within one of my Views which accepts a ViewModel. I am using Data Annotations which I have placed on the properties I wish to validate.
ViewModel
public class ViewModelShiftDate
{
public int shiftDateID { get; set; }
public int shiftID { get; set; }
[DisplayName("Start Date")]
[Required(ErrorMessage = "Please select a Shift Start Date/ Time")]
public DateTime? shiftStartDate { get; set; }
[DisplayName("Assigned Locum")]
public int assignedLocumID { get; set; }
public SelectList AssignedLocum { get; set; }
}
View
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<br />
<div class="editor-label">
@Html.LabelFor(model => model.shiftStartDate)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.shiftStartDate, new { @readonly = "readonly" })
@Html.ValidationMessageFor(model => model.shiftStartDate)
</div>
<br />
<div class="editor-label">
@Html.LabelFor(model => model.assignedLocumID)
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.assignedLocumID, Model.AssignedLocum)
@Html.ValidationMessageFor(model => model.assignedLocumID)
</div>
<br />
<p>
<input type="submit" value="Save" />
</p>
<br />
}
The SelectList ‘AssignedLocum‘ is passed into my View for a DropDownList, and the item selected is assigned to the property ‘assignedLocumID‘.
As you can see from my ViewModel, the only required field is ‘shiftStartDate‘, however, when I hit the Submit button in my View, the drop down list ‘AssignedLocum‘ also acts a required field and will not allow the user to submit until a value is selected.
Does anyone know why this property is acting as a required field even though I have not tagged it to be so?
Thanks.
Try to use default value for dropdown (for example “Please select”)