asp.net - ASP.NET MVC 中的验证触发

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

我对我正在从事的这个 MVC 项目迷失了方向。我还读过布拉德·威尔逊的文章。 http://bradwilson.typepad.com/blog/2010/01/input-validation-vs-model-validation-in-aspnet-mvc.html

我有这个:

public class Employee
{
    [Required]
    public int ID { get; set; }
    [Required]
    public string FirstName { get; set; }
    [Required]
    public string LastName { get; set; }
}

这些在 Controller 中:

public ActionResult Edit(int id)
{
    var emp = GetEmployee();
    return View(emp);
}

[HttpPost]
public ActionResult Edit(int id, Employee empBack)
{
    var emp = GetEmployee();
    if (TryUpdateModel(emp,new string[] { "LastName"})) {
        Response.Write("success");
    }
    return View(emp);
}

public Employee GetEmployee()
{
    return new Employee {
       FirstName = "Tom",
       LastName = "Jim",
       ID = 3
    };
}

我的观点如下:

<% using (Html.BeginForm()) {%>
    <%= Html.ValidationSummary() %>

    <fieldset>
        <legend>Fields</legend>    
        <div class="editor-label">
            <%= Html.LabelFor(model => model.FirstName) %>
        </div>
        <div class="editor-field">
            <%= Html.DisplayFor(model => model.FirstName) %>
        </div>

        <div class="editor-label">
            <%= Html.LabelFor(model => model.LastName) %>
        </div>
        <div class="editor-field">
            <%= Html.TextBoxOrLabelFor(model => model.LastName, true)%>
            <%= Html.ValidationMessageFor(model => model.LastName) %>
        </div>
        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>

<% } %>

请注意,唯一可编辑的字段是姓氏。当我回发时,我返回原始员工并尝试仅使用 LastName 属性来更新它。但是我在页面上看到以下错误:

•名字字段为必填项。

据我了解,这是因为 TryUpdateModel 失败。但为什么?我告诉它只更新 LastName 属性。

我正在使用 MVC2 RTM

提前致谢。

最佳答案

问题是,当您的表单被发回时,FirstName 字段为空。问题是,由于您将 Employee 作为参数传递给操作,因此验证会在您有机会调用 GetEmployee() 之前发生。您可以执行以下三件事之一:

1) 从 FirstName 字段中删除 [Required] 属性。

2)为此字段添加Html.HiddenFor(),以便它将进行往返。像这样:

<%= Html.HiddenFor(model => model.FirstName) %>

3) 将您的操作声明更改为:

public ActionResult Edit(int id, FormCollection form)

(3) 可能就是您正在寻找的内容。

关于asp.net - ASP.NET MVC 中的验证触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2556813/

相关文章:

jquery - ASP.NET MVC : how to detect when a page is called using ajax

javascript - IE 11 不向 Web 应用程序发送 CORS 'POST' 请求

asp.net-mvc - 在多个 ASP.NET MVC 2 项目之间共享数据模型和控件的最佳方式

asp.net - 是否有人使用Iron speed Designer进行asp.net的快速开发?

c# - Asp.net 中的析构函数

asp.net - 带有自定义 Web UI 的 SSRS

jquery - 使用 JQuery 在 ASP.Net MVC 中加载部分 View - 首选哪种方法?

asp.net-mvc - 现有的 MVC2 应用程序可以迁移到 Azure 云服务项目吗?

css - 不知道如何编写我的 css

c# - 使用 httpcontext 打开附件