Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC UpdateModel throws exception: "Model could not be updated"

Tags:

asp.net-mvc

Im trying to update a simple model in MVC,but its not working,it throws an exception saying that the Model could not be updated:

      [HttpPost]
        public ActionResult SignIn([Bind(Exclude="TxtEmail")]Usuarios usuario,FormCollection fc)
        {
            try
            {
                UsuariosModel userModel = new UsuariosModel(usuario);
                userModel.Usuarios.TxtEmail = "[email protected]";

                UpdateModel(userModel);

                if (ModelState.IsValid)
                {
                 [...]
                }
                [...]
        }

This is the model:

[Required(ErrorMessage="**O email é requerido")]
[RegularExpression("^[a-z0-9_\\+-]+(\\.[a-z0-9_\\+-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*\\.([a-z]{2,4})$",ErrorMessage="**Email Inválido")]
public string TxtEmail
{
    get { return this.txt_email; }
    set { this.txt_email = value; }
}

How can i use this method "UpdateModel"?

like image 702
ozsenegal Avatar asked Oct 28 '10 12:10

ozsenegal


2 Answers

Maybe your data does not match the validation.

I would try TryUpdateModel.

The TryUpdateModel method is like the UpdateModel method except that the TryUpdateModel method does not throw an InvalidOperationException exception if the updated model state is not valid.

like image 177
GvS Avatar answered Oct 15 '22 16:10

GvS


Look in your ModelState entries ( accessible with this.ModelState ).

ModelState contains an entry for each property and the errors for that property in the model you are trying to bind. Chances are you are passing the wrong datatype along in the post or get action.

like image 29
John Farrell Avatar answered Oct 15 '22 14:10

John Farrell