Jim H
Jim H

Reputation: 294

Use same actionresultmethod for multiple viewmodels?

I have three viewmodels to edit the same domain object. I use AutoMapper to map to viewmodels from the domain object.

GET

if (Roles.IsUserInRole("administrators"))
{
    viewName = "EditAdmin";
    editOrder = Mapper.Map<Order, ViewModels.Order.Admin_ViewModel>(order);
}
else if (Roles.IsUserInRole("administrators"))
{
    viewName = "EditTechnician";
    editOrder = Mapper.Map<Order, ViewModels.Order.Technician_ViewModel>(order);
}
else if (Roles.IsUserInRole("clients"))
{
    viewName = "EditClient";
    editOrder = Mapper.Map<Order, ViewModels.Order.Client_ViewModel>(order);
}

RedirectToRoute(viewName, editOrder);

POST Is it possible to use the same method for all viewmodels? Possibly by letting the ViewModels inherit from "ViewModelbase"? Tried this with no success :(

Many thanks in advance!

EDIT: This is what my method looks like now:

public ActionResult EditAdmin(ViewModels.Order.Admin_ViewModel model) {...}

Any ideas?

UPDATE: I wasn't able to understand how to use composition (tried it for a few hours). So I went with this to clean up a bit. These are the handlers for my three viewmodels:

[HttpPost]
[Authorize(Roles = "administrators")]
public ActionResult EditAdmin(Admin_ViewModel model)
{
    return SaveViewModel(model);
}

[HttpPost]
[Authorize(Roles = "technicians")]
public ActionResult EditTechnician(Technician_ViewModel model)
{
    return SaveViewModel(model);
}

[HttpPost]
[Authorize(Roles = "clients")]
public ActionResult EditClient(Client_ViewModel model)
{
    return SaveViewModel(model);
}

SaveViewModel looks like this:

protected ActionResult SaveViewModel(dynamic model)
{ ... }

I don't feel to good about this solution. Could you please give me some pointers?

Upvotes: 2

Views: 71

Answers (1)

Rajeesh
Rajeesh

Reputation: 4495

IMHO - ViewModel should plain and simple. If you introduce inheritance, it is going get complicated.

I suggest you to use composition to build the ViewModel you want. So if the user is in a particular role, objects which are not related to the Role will be null when the page is posted. With that you can stick to one POST method rather than many.

Update : If you really want to have the inheritance in ViewModel. Custom model binder is the solution, if the default one is not working

Upvotes: 1

Related Questions