I have a SQL Server 2012 in which I have AWARD table with two columns TITLE and MONTH. TITLE is varchar(256) and cannot be NULL. MONTH is int and can be NULL.
With VS2012 Ultimate and EF 5.0.0, the TextBoxFor helper in MVC4 app is not producing validation (data-val="required" and data-val-required="required message")
for the TITLE columne above, but in the same View, MONTH is getting the correct validation markup. The .edmx designer does show TITLE is NonNullable, BUTT, the automatically generated AWARD.cs file does not have the [Required]
attribute for the TITLE column.
What can I try?
@model MyProject.Models.AWARD
@{
ViewBag.Title = "Add Award";
Layout = "~/Views/Shared/_EditorLayout.cshtml";
}
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Add Award</legend>
<table>
<tr>
<td>
@Html.LabelFor(model => model.TITLE)
</td>
<td>
@Html.TextAreaFor(model => model.TITLE)
<br />@Html.ValidationMessageFor(model => model.TITLE)
</td>
</tr>
<tr>
<td>
@Html.LabelFor(model => model.MONTH)
</td>
<td>@Html.DropDownListFor(model => model.MONTH, new SelectList(MyProject.Models.Helpers.Months, "key","value"), "[Not Selected]")
<br />@Html.ValidationMessageFor(model => model.MONTH)
</td>
</tr>
<tr>
<td>
<input type="submit" value="Add" />
</td>
<td>
@Html.ActionLink("Cancel", "Index", null, new { @class = "cancel-button" })</td>
</tr>
</table>
</fieldset>
}
You shouldn't really be binding your views directly to your data mapping entities. You should create view model classes to wrap the data you pass to and from your view and then populate your data objects from the controller.
You can then perform the required validation on your view model without affecting your generated mapping classes.
Model
View
Controller