ASP.NET MVC si Validarea Model Binder

Ca in ASP.NET MVC Best Practices( aici, aici, aici, aici si aici ) am pus o metoda in Controller care sa faca legatura automat cu acea clasa ce trebuie salvata:

 

[AcceptVerbs(HttpVerbs.Post)]
        [Authorize()]
        public ActionResult Index([Bind(Exclude = "IDAlert,IDPerson", Prefix = "")]CV_Alerte c)
        {}

Insa am avut o problema subtila : CV_Alerte are un membru Valoare de tipul double care este mapat la un textbox. Ce se intimpla daca trimit xxx ?

La o cautare rapida pe net, gasesc raspunsul : Verifica ModelState.IsValid . OK, si acum cum iau eroarea ? Nu am gasit pe net, asa ca, dupa o investigare rapida a surselor, am gasit metoda:

if (!ModelState.IsValid)
            {
                foreach (var s in ModelState.Keys)
                {
                    if (!ModelState.IsValidField(s))
                    {
                        ModelState.AddModelError(s,"aveti o eroare la setarea " + s + "–" + ModelState[s].Value.AttemptedValue);
                    }
                }
                return View();
            }

Ar fi trebuit sa o faca ei!

Ca referinta la ASP.NET Best Practices:

http://weblogs.asp.net/rashid/archive/2009/04/01/asp-net-mvc-best-practices-part-1.aspx
http://weblogs.asp.net/rashid/archive/2009/04/03/asp-net-mvc-best-practices-part-2.aspx
http://www.lostechies.com/blogs/jimmy_bogard/archive/2009/04/24/how-we-do-mvc.aspx
http://codeclimber.net.nz/archive/2009/04/17/how-to-improve-the-performances-of-asp.net-mvc-web-applications.aspx  http://blog.maartenballiauw.be/post/2009/05/06/More-ASPNET-MVC-Best-Practices.aspx

si,bineinteles, eu 😉

Leave a Reply

Your email address will not be published. Required fields are marked *