Render different view depending on the type of the data

Posted by Miau on Stack Overflow See other posts from Stack Overflow or by Miau
Published on 2010-05-24T07:41:15Z Indexed on 2010/05/24 7:51 UTC
Read the original article Hit count: 195

Filed under:

Hi there

So lets suppose we have an action in a controller that looks a bit like this:

public ViewResult SomeAction(int id)
{
    var data = _someService.GetData(id);
    ...
    //create new view model based on the data here
   return View(viewModel);
}

What I m trying to figure out is the best way to render a diferent view based on the type fo the data. the "_someService.GetData method returns an data that knows its out type (ie not only you can do typeof(data) but also you can do data.DataType and you ll get an enum value so I could achieve what I m trying to do doing something kinda like this

public ViewResult SomeAction(int id)
{
    var data = _someService.GetData(id);

    //I m  mapping fields to the viewModel here
    var viewModel = GetViewModel(data); 

   swtich(data.DataType) 
     case DataType.TypeOne:  return View("TypeOne", viewModel); break;
   ...


}

But this does not seem to be the nicest way, (I dont event know if it would work) Is this the way to go? Should I use some sort of RenderPartial Aproach? after all , waht will change in the view is mostly the order of the data (ie the rest of the view would be quite similar) Cheers

© Stack Overflow or respective owner

Related posts about asp.net-mvc