开发者

Adding services to a user using multiple selections in MVC3

I have a problem an开发者_运维知识库d don't know where to start as I am new to MVC. I have three tables:

  • User (UserID, Username, etc...) This defines users.
  • Service (ServiceID, ServiceName, etc...) This defines services.
  • Licenses (ID, UserID, ServiceID, etc...) Maps services to a user.

In the back-end the user can access a service if he has a license. Ideally I would like a list of services in my EditUser view where I could check which services they should have licenses to.

This list needs to pre-populate with current licenses and if one is unchecked and saved it needs to be deleted.

I have all the methods to add and remove licenses, but I need to know how to implement this in my controller and view.

Thanks in advance.


First of all, define a ViewModel

public class EditUserViewModel
{
    public User User { get; set; }
    public IList<License> Licenses { get; set; }
    public IList<Service> Services { get; set; }
}

A View Model is simply a helper class that contains everything that you'll need to display a view. Then, in your action:

public ActionResult EditUser(int id)
{
    var userViewModel = new EditUserViewModel
    {
        User = // Get user from db
        Licenses = // Get licenses for that user
        Services = // Getservies the user in entitled to   
    }

    return View(userViewModel); 
}

Then, make your view a typed view with EditUserViewModel for model:

@model EditUserViewModel

@* //Some html or whatever here *@

@* //Access your model properties as follows *@
@Model.User
@Model.Licenses
@Model.Service    

You can reuse the EditUserViewModel class for other views, UserDetails, for instance. In that case you might want to rename and get rid of the "Edit" prefix.

UPDATE to clarify question in comments: Rule of thumb: Keep your view models small, dumb and simple. No methods, functionality or intelligence, just a couple of properties that assist you in the display process. You'll only want to reuse View Models on views that are very similar, like would be the case with an EditUser and DisplayUser view. You'd have a different view model for a DisplayServices view, etc.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜