Why does MVC call set methods on my model when my string is too long?

331 views Asked by At

In an ASP.NET MVC application, I have a model defined as follows:

public class TestModel
{
    private string _firstName;

    [DisplayName("First Name")]
    [StringLength(20)]
    public string FirstName
    {
        get { return _firstName; }
        set
        {
            if (!string.IsNullOrEmpty(value))
                if (value.Length > 20)
                    throw new Exception("Too long");

            _firstName = value;
        }
    }
}

In my controller Update action method, I have the following code:

[HttpPost]
public ActionResult Update()
{
    var tm = new TestModel();
    if (ModelState.IsValid)
    {
        if (TryUpdateModel(tm))
        {
            // Save to the DB
        }
    }

    return View("Test", tm);
}

The problem is that when I enter a value into the textbox in my view that is longer than 20 characters I expect that MVC wouldn't try to set the property on my model (which then throws an exception because it's too long to fit in the DB column). I would have thought that it would be stopped by the ModelState.IsValid test before actually trying to set the property.

Note, I'm simulating an actual ORM here - LLBLGenPro - which is what it does on its generated properties for database columns that have a length - it throws an exception if you try to set a value that is too long.

How should I fix this problem, apart from modifying the templates for LLBLGen?

Is this normal behaviour for ASP.NET MVC?

1

There are 1 answers

0
YavgenyP On

Your code, as provided, doesnt receive the model instance from the view, and you are creating the instance of the class in ur code, so its impossible to tell
this code:

var tm = new TestModel();   

creates the instance of Testmodel, but its not binded in anyway to the values received from the posted form. Your action should basicly look like

public ActionResult Update(TestModel model) 

and this is the instance of model mvc will try to validate.
Maybe you should post ur entire code (including the view) to see if anything else is missing, but with the code you provide so far, you will never have your forms values updated in the repository, nor you will have the exception thrown, because FirstName will remain null.