views:

44

answers:

2

Hi, 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.

+3  A: 

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.

Darin Dimitrov
thanks but I'm already doing this and it's still saying it's valid when it clearly isn't! :(
Lisa
A: 

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

}
Simon Hazelton
yes I tried a test app and it seemed to work fine on that - I'm incorporating this new mvc project on top of an existing webform framework - do you think there is something I might have missed in web.config or global asax??
Lisa
Might be worth checking framework versions on the target site. Nothing obvious springs to mind, I guess this is one of those reasons you get paid :)
Simon Hazelton
Hi thanks for that but I think there was some conflicts with my structureMapController in global asax file (needed for dependency injection for unit tests) So in the end instead of using the DataAnnotations for validation I used the Microsoft Enterorise library validations instead and it works FINALLY !! - thanks everyone for trying to help though :)
Lisa