Tuesday 15 November 2011

MVC metadata attribute [ReadOnly(bool)]

Discovered a little odd validation bug/Quirk which tripped me up for a wee while.
The metadata attribute [ReadOnly(bool)] : which seems ideal for Server/db Generated IDs etc as shown below.

   public class MyMetaData 
    {
        [ReadOnly(true)]
        public object Id { get; set; }
The View is setup to use a Model for Editing so it already has an Id not zero  (ie Id = 3 for third record in the database).

ie  @model UserModel 

This however has an odd little quick when a form is posted back to a controller.
for example 

[HttpPost]
public ActionResult Edit(UserModel user)
{
           Console.Writeline(user.Id);
The  user.Id will always be 0 (the default for Int), This is directly linked to using the MetaData attribute

   [ReadOnly(true)]

BackGround:
If you supply a ViewModel to a View and the submit a form in the View back to a controller (ie the parameter in the controller action is a viewmodel) the view will store the unused values from that model (not displayed or used on the view) back to the controller.
In my example below I submit a UserModel to the form and accept this back into Controller again. I don't display all the fields in this Model such as UserID, Password etc.  But MVC is smart enough to retain these for later use, this is much better than ASP.NET, although passing very large models for a handful of fields could deter good performance.

.... Controller.....
        //GET  UserMode for Edit 
        public ActionResult Edit(int userid)
        {
            UserModel user = MyServiceLayer.GetUder(userId)
            return View(user);
        }
        [HttpPost]
        public ActionResult Edit(UserModel user)
        {        
            UserService.SaveUser(user);
            return RedirectToAction("Index");
        }


No comments:

Post a Comment

Comments are welcome, but are moderated and may take a wee while before shown.