开发者

Design problem with MVC 3.0

I have a View User :

public class User {
   public int id { get; set; }
   public string name { get; set; }
   public string email { get; set; }    开发者_JAVA百科
}

I created a login View (strongly typed User)... But my Login view has others attributes, like RememberMe checkbox... That attribute does not belong to User Model...

So, how is the best way to deal with that? Creating a new UserViewModel with all View attributes is an option, but I think its not the best way...

Paul


So, how is the best way to deal with that?

By using a view model:

public class LoginViewModel
{
    public string Username { get; set; }
    public string Password { get; set; }  
    public bool RememberMe { get; set; }  
}

Strongly typing a login partial to a User model hardly makes sense.


For best practices I would suggest you use a ViewModel as Darin suggested. Also u can create a factory for copying ViewModel to Entity. Reflection is a bit too much here.

Here is just Darin Dimitrov example in detail.

    public class User
{
    public string Username { get; set; }
    public string Password { get; set; }
    public bool RememberMe { get; set; }
}

public class LoginViewModel
{
    [Required] ... and other validation
    public string Username { get; set; }
    public string Password { get; set; }
    public bool RememberMe { get; set; }
}

public static class UserFactory
{
    public static User GetUserFromModel(LoginViewModel m, User u)
    {
        u.Username = m.Username;
        u.Password = m.Password;
        return u;
    }
}

public class UserController : DefaultController
{
    public ActionResult Login(LoginViewModel m)
    {
        if (ModelState.IsValid)
        {
            User u = UserFactory.GetUserFromModel(m);
            ....code ...
        }
        ... code...
    }

}

@Darin sorry for highjacking your example, I remember having a bit of hard time with this myself so just want to help

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜