【问题标题】:ASP.NET MVC 2 RC Validation problemASP.NET MVC 2 RC 验证问题
【发布时间】:2009-12-26 05:45:35
【问题描述】:

我正在尝试使用 ASP.NET MVC 2 (RC) 的验证功能

我有一个

视图模型

public class CategoryPageViewModel
{

            public int Id { get; set; }

            [Required(ErrorMessage="Category name required")]
            public string CategoryName { get; set; }
}

动作

    [HttpPost()]
    public ActionResult Create(CategoryPageViewModel categoryModel)
    {
        if (ModelState.IsValid)
        {
            return View("Completed");
        }
        return View(categoryModel);

    }

查看

<%= Html.ValidationSummary() %>

<% using (Html.BeginForm("Create", "Category", FormMethod.Post)) {%>

    <fieldset>
        <legend>Create new category</legend>
        <p>
            <label for="CategoryName">Category name:</label>
            <%= Html.TextBox("CategoryName") %>
            <%= Html.ValidationMessage("CategoryName", "*")%>
        </p>

        <p class="submit">
            <input type="submit" value="Create" />
        </p>
    </fieldset>

<% } %>

提交时说 id 字段也是必需的,但我没有设置Required 属性。

我做错了什么还是一个错误?这是今天 26/12/09 下载的 RC 版本。

【问题讨论】:

    标签: asp.net-mvc validation asp.net-mvc-2


    【解决方案1】:

    您的 Create 方法正在尝试从已发布的表单集合中构造一个新的 CategoryPageViewModel

    public ActionResult Create(CategoryPageViewModel categoryModel){...}
    

    但是,由于您的表单仅包含 CategoryName 的输入,因此您的控制器方法无法创建需要 id 的新 CategoryPageViewModel

    您的问题有两种解决方案:

    1. 如@Andrew 所述,使CategoryPageViewModel 中的Id 可以为空。

      public int? Id { get; set; }
      
    2. 推荐解决方案: 保持 Id 不可为空,但在表单中将此值呈现为隐藏输入。这将允许您保持系统 ID 完整,从控制器查看并再次返回。

      在视图中添加 Id 作为隐藏输入,使用以下代码:

      <%= Html.Hidden("Id") %>
      

    【讨论】:

      【解决方案2】:

      如果您不想传入 Id,请将其设为可空...即:

      public class CategoryPageViewModel
      {
                  public int? Id { get; set; }
      
                  [Required(ErrorMessage="Category name required")]
                  public string CategoryName { get; set; }
      }
      

      或者根本不包括它。您希望如何在没有 ID 的情况下执行任何类型的数据库更新?

      【讨论】:

      • Id 将由 db 自动生成。只有在编辑类别或将类别分配给另一个相关对象时才需要 ID。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-21
      • 1970-01-01
      • 2011-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多