Inside model I have data annotations:
[Required(ErrorMessageResourceName = "SelectCategory", ErrorMessageResourceType = typeof(MyProject.Properties.Resources)), Range(1, int.MaxValue, ErrorMessageResourceName = "SelectCategory", ErrorMessageResourceType = typeof(MyProject.Properties.Resources))]
public int CategoryId { get; set; }
public virtual Category Category { get; set; }
and two situations:
Situation1
Inside controller I have
List<Category> categories = db.GetCategories();
ViewBag.CategoryId = categories;
Inside View:
<div class="form-group">
@Html.LabelFor(model => model.CategoryId, htmlAttributes: new { @class = "control-label col-md-3" })
<div class="col-md-6">
@Html.DropDownListFor(model => model.CategoryId, new SelectList(ViewBag.CategoryId, "Id", "Name", 2), htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.CategoryId, "", new { @class = "text-danger" })
</div>
</div>
Html result:
<div class="form-group">
<label class="control-label col-md-3" for="CategoryId">Category</label>
<div class="col-md-6">
<select class="form-control" data-val="true" data-val-number="The field Category must be a number." data-val-range="Select category" data-val-range-max="2147483647" data-val-range-min="1" data-val-required="Select category" id="CategoryId" name="CategoryId">
<option value="0">---Select---</option>
<option value="1">Cat1</option>
<option value="2">Cat2</option>
<option value="3">Cat3</option>
</select>
<span class="field-validation-valid text-danger" data-valmsg-for="CategoryId" data-valmsg-replace="true"></span>
</div>
</div>
I have validation attributes inside 'select' element, but no selected element
Situation2:
Inside controller I have
List<Category> categories = db.GetCategories();
ViewBag.CategoryId = new SelectList(categories, "Id", "Name", 2);
Inside View:
<div class="form-group">
@Html.LabelFor(model => model.CategoryId, htmlAttributes: new { @class = "control-label col-md-3" })
<div class="col-md-6">
@Html.DropDownList("CategoryId", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.CategoryId, "", new { @class = "text-danger" })
</div>
</div>
Html result:
<div class="form-group">
<label class="control-label col-md-3" for="CategoryId">Category</label>
<div class="col-md-6">
<select class="form-control" id="CategoryId" name="CategoryId">
<option value="0">---Select---</option>
<option value="1">Cat1</option>
<option selected="selected" value="2">Cat2</option>
<option value="3">Cat3</option>
</select>
<span class="field-validation-valid text-danger" data-valmsg-for="CategoryId" data-valmsg-replace="true"></span>
</div>
</div>
I have no validation attributes inside 'select' element, but I have selected element
Could anyone explain me what is wrong? What should I do to have validation attributes and selected option?