开发者

Casting Object type in mvc controller

I have the folowing class and controller (mvc)

UI Model inherits DB model (ef4.0)

public class RegistrationModel : Model.User
    {
        [Required]
        public string PasswordText { get; set; }
    }   

MVC controller

    public ActionResult Create(RegistrationModel registrationModel)
            {
                try
                {
                    Context ctx = new Context();
                    Model.User user = new Model.User();
                    user = (registrationModel as Model.User);
                    user.Password = System.Text.ASCIIEncoding.ASCII.GetBytes(registrationModel.PasswordText); //do encryption later on
...
                    ctx.Customer.Add(registrationModel as Model.User);
                    ctx.SaveChanges();
                }
    }

when i cast the registrationmodel to a开发者_运维百科 user the type remains registrationmodel is there a way to cast it, without copying all its properties to a new user object?

                Model.User user = new Model.User();
                user.Active = registrationModel.Active;
                user.Blocked = registrationModel.Blocked;
//...

....


How about using AutoMapper. Brilliant for automatically mapping data from models to view models and so on.


correct. I had the same issue. it seems that all types of casting (document in MSDN here: http://msdn.microsoft.com/en-us/library/ms173105.aspx) does not seem to work in MVC controllers.

for instance:

// IRREGULAR MVC CONTROLLERS BEHAVIOR 
// implicit casting
Model.User user = registrationModelInstance // won't case to base
// explicit casting
Model.User user = (Model.User)registrationModelInstance // won't case to base

i ended up using AutoMapper (similar to User-Defined conversion per MSDN). should look like that:

Mapper.CreateMap<RegistrationModel, Model.User>();
Mapper.Map<RegistrationModel, Model.User>(registrationModelInstance);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜