TextBoxFor() not generating validation markup

99封情书 提交于 2019-12-04 05:30:27

问题


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>
}

回答1:


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

public class AwardViewModel
{
    [Required, StringLength(30)]
    public string Title { get; set; }
    ....
}

View

@model AwardViewModel

@using (Html.BeginForm()) {
    @Html.EditorFor(m => m.Title)
    @Html.ValidationMessageFor(m => m.Title)
    ...
}

Controller

[HttpPost]
public ActionResult Create (AwardViewModel model)
{
    /* Create new AWARD in entity context, populate
       with relevant fields from model and commit. */
}


来源:https://stackoverflow.com/questions/14531644/textboxfor-not-generating-validation-markup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!