MVC验证不适用于Web窗体项目

时间:2010-07-13 13:48:54

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

我的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 Forms项目中,但是MVC项目运行正常,只是验证不起作用,任何想法?感谢。

2 个答案:

答案 0 :(得分:3)

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

public ActionResult SomeAction(MyModel model)
{
    if (ModelState.IsValid)
    {

    }
    return View();
}

现在,如果您调用:

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

模型不应该有效。

答案 1 :(得分:0)

嗯,它适用于我的测试页面,包含以下内容

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

}