tags:

views:

43

answers:

3

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"?

+1  A: 

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.

GvS
A: 

you are using the UpdateModel() wrong.

you are supposed to get the original object from your database. and input that into UpdateModel()

UpdateModel() will 'read' the fields from your FormCollection.

Stefanvds
What if he's doing an insert/add operation?
jfar
can you insert items using the updatemodel??
Stefanvds
No, but if I was adding an item I would go var prod = new Product(); UpdateModel(prod) which is exactly what he's doing.
jfar
A: 

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.

jfar
thk for your help.Ive figure out that UpdateModel takes values from FormCollection or from your Strong-Typed Model passed in as parameter.