开发者

MVC Validation Not Working In Web Forms Project

I have the following code in my aspx view page:

<% using (Html.BeginForm())
    { 
 %>
<div>
    CustomerCode:&nbsp;
    <%= Html.TextBoxFor(x=>  x.开发者_运维知识库CustomerCode) %>
    <%= Html.ValidationMessageFor(x => x.CustomerCode)%>

and this code in my model:

public class MyModel
{

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

Though if I enter more than 2 charachters in the textbox and submit the page, in the controller when I do:

        if (ModelState.IsValid)

It always says its valid? What am I missing? I have put this MVC project inside a Web Forms project but the MVC project works fine, its just the validation which is not working, any ideas? Thanks.


Make sure that the controller action accepts the model as parameter:

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

    }
    return View();
}

Now if you invoke:

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

The model should not be valid.


Hmm, it works for me on a test page with the following

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

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜