Skip to main content
 首页 » 编程设计

c#之TextBoxFor() 不生成验证标记

2024年02月20日16rubylouvre

我有一个 SQL Server 2012,其中我有一个包含两列 TITLE 和 MONTH 的 AWARD 表。 TITLE 是 varchar(256),不能为 NULL。 MONTH 是一个整数,可以为 NULL。

在 VS2012 Ultimate 和 EF 5.0.0 中,MVC4 应用程序中的 TextBoxFor 助手不会生成验证 (data-val="required"and data-val-required="required message")上面的 TITLE 列,但在同一个 View 中,MONTH 得到了正确的验证标记。 .edmx 设计器确实显示 TITLE 是 NonNullable,但是,自动生成的 AWARD.cs 文件没有 [Required] TITLE 列的属性。

我可以尝试什么?

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

请您参考如下方法:

您真的不应该将您的 View 直接绑定(bind)到您的数据映射实体。您应该创建 View 模型类来包装您传入和传出 View 的数据,然后从 Controller 填充数据对象。

然后您可以在不影响生成的映射类的情况下对 View 模型执行所需的验证。

型号

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

查看

@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. */ 
}