0

我是 MVC 的新手,并且仍然在为我认为非常基本的 mvc 东西而苦苦挣扎。我的预期目的只是呈现代表数据对象集合的文本框,以便我可以使用 DataAnnoations 轻松验证它们。我已经阅读并理解了本教程,并且已经让它工作得很好——但它一次只验证一个人对象,由原语组成:

http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx

我的问题与这篇文章类似,但我没有成功地将其应用于没有 Razor 的情况:

使用数据注释对集合进行 MVC 3 客户端验证 - 不起作用

验证在 String 和 int 等“原语”上效果很好,但我不明白对集合的验证。

这是代表我的对象的一个​​实例和一些验证的类:

public class vc_EBTOCRecord
{
    [StringLength(10, ErrorMessage = "must be under 10 chars")]
    [Required(ErrorMessage = "Problem!")]
    public String ItemText;
}

这是视图继承的模型:

public class EBTOCViewModel
{
    public List<vc_EBTOCRecord> VcEbtocRecordList { get; set; }

}

这是我的控制器:

     public ActionResult Create()
    {
        EBTOCViewModel ebtocViewModel = new EBTOCViewModel();
        List<vc_EBTOCRecord> vcEbtocRecordList = new List<vc_EBTOCRecord>();

        vc_EBTOCRecord vcEbtocRecord = new vc_EBTOCRecord();
        vcEbtocRecord.ItemText = "bob";
        vcEbtocRecordList.Add(vcEbtocRecord);

        vc_EBTOCRecord vcEbtocRecord2 = new vc_EBTOCRecord();
        vcEbtocRecord.ItemText = "fred";
        vcEbtocRecordList.Add(vcEbtocRecord2);

        vc_EBTOCRecord vcEbtocRecord3 = new vc_EBTOCRecord();
        vcEbtocRecord.ItemText = "joe";
        vcEbtocRecordList.Add(vcEbtocRecord3);

        ebtocViewModel.VcEbtocRecordList = vcEbtocRecordList; 

        return View(ebtocViewModel);
    } 

最后,我认为这是我正在尝试的:

    <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<vcAdminTool.ViewModels.EBTOCViewModel>" %>
    <h2>Create</h2>

<% using (Html.BeginForm()) {%>
    <%: Html.ValidationSummary(true) %>

    <fieldset>
        <legend>Fields</legend>
        <% foreach(var thing in Model.VcEbtocRecordList)
           {
               Html.TextBoxFor(model => thing.ItemText);       
               //Html.TextBox("hello", thing.ItemText );  didn't work...
               //Html.TextBox("hello");  nope, still didn't work
              Response.Write("a record is here");
           }
             %>
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>

<% } %>

<div>
    <%: Html.ActionLink("Back to List", "Index") %>
</div>

当视图渲染时,“a record is here”被打印了三遍,这表明 MVC 可以识别我创建的底层对象,但为什么它不会渲染三个文本框?

期望的结果是有三个空白的验证文本框。然后,如果表单有效,我将编写将信息写回数据库的代码。

如果你愿意,我错过了什么明显的东西?

4

0 回答 0