【问题标题】:MVC Validation Not Working In Web Forms ProjectMVC 验证在 Web 表单项目中不起作用
【发布时间】:2010-07-13 13:48:53
【问题描述】:

我的 aspx 视图页面中有以下代码:

<% using (Html.BeginForm())
    { 
 %>
<div>
    CustomerCode:&nbsp;
    <%= Html.TextBoxFor(x=>  x.CustomerCode) %>
    <%= Html.ValidationMessageFor(x => x.CustomerCode)%>

我的模型中的这段代码:

public class MyModel
{

    [Required(ErrorMessage="customer code req")]
    [StringLength(2,ErrorMessage="must be 2 u idiot")]
    public string CustomerCode {get; set;}

虽然如果我在文本框中输入超过 2 个字符并提交页面,但当我这样做时在控制器中:

        if (ModelState.IsValid)

它总是说它有效?我错过了什么?我已将此 MVC 项目放在 Web 窗体项目中,但 MVC 项目工作正常,只是验证不起作用,有什么想法吗?谢谢。

【问题讨论】:

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


    【解决方案1】:

    确保控制器动作接受模型作为参数:

    public ActionResult SomeAction(MyModel model)
    {
        if (ModelState.IsValid)
        {
    
        }
        return View();
    }
    

    现在如果你调用:

    http://example.com/myapp/home/someaction?customercode=123
    

    模型应该是无效的。

    【讨论】:

    • 谢谢,但我已经在这样做了,它仍然说它是有效的,但显然不是! :(
    【解决方案2】:

    嗯,它在测试页面上对我有用

        public ActionResult Test()
        {
            MyModel model = new MyModel();
            return View(model);
        }
    
        [HttpPost]
        public ActionResult Test(MyModel model)
        {
            if (ModelState.IsValid) { }
            return View(model);
        }
    
    <% using (Html.BeginForm()) {%>
        <%: Html.ValidationSummary(true) %>
    
        <fieldset>
            <legend>Fields</legend>
    
            <div class="editor-label">
                <%: Html.LabelFor(model => model.CustomerCode) %>
            </div>
            <div class="editor-field">
                <%: Html.TextBoxFor(model => model.CustomerCode) %>
                <%: Html.ValidationMessageFor(model => model.CustomerCode) %>
            </div>
    
            <p>
                <input type="submit" value="Create" />
            </p>
        </fieldset>
    
    <% } %>
    
    public class MyModel
    {
        [Required(ErrorMessage = "customer code req")]
        [StringLength(2, ErrorMessage = "must be 2 u idiot")]
        public string CustomerCode { get; set; }
    
    }
    

    【讨论】:

    • 是的,我尝试了一个测试应用程序,它似乎运行良好 - 我正在将这个新的 mvc 项目合并到现有的 webform 框架之上 - 你认为我可能错过了什么web.config 还是全局 asax??
    • 可能值得检查目标站点上的框架版本。没有什么明显的想法,我想这是你获得报酬的原因之一 :)
    • 您好,感谢您,但我认为在全局 asax 文件中与我的 structureMapController 存在一些冲突(需要用于单元测试的依赖注入)所以最后我没有使用 DataAnnotations 进行验证,而是使用了 Microsoft Enterorise 库验证,它终于可以工作了! - 感谢大家尝试提供帮助 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-24
    • 1970-01-01
    • 1970-01-01
    • 2021-08-28
    • 1970-01-01
    • 2021-12-01
    相关资源
    最近更新 更多