How do I display the correct view based on the model's "type"?
I have a database that is set up using EF Table Per Type, and I am trying to write a details View in Razor for the details page. The tricky part is that I have a base class Product
and two derived classes VideoProduct
and DatabaseProduct
, and I want to display them all in a list View and be able to provide a details View for each type. I am having trouble figuring out how to determine which View to return depending on the type of object that comes back from the database. Here is some of the code:
MODELS:
public abstract class Product
{
// some properties
}
public class DatabaseProduct
{
int SpecialInvoiceID { get; set; }
}
public class VideoProduct
{
public virtual ICollection<FilmsCollection> FilmsCollectionIDs { get; set; }
public virtual ICollection<OtherCollection> OtherCollectionIDs { get; set; }
}
CONTROLLER:
public ActionResult Details(int id)
{
var product = db.Products.Find(id); // could be a VideoProduct or a DatabaseProduct
if (product == null)
return RedirectToAction("Index");
return View("Details", product);
}
VIEW:
What do I do here to allow the details View to display either type开发者_Python百科 of Model? Or what can I do in the Controller to call different Views to display for different Model Classes? Or can I use DisplayForModel?
I tried to find an example of this through Google, but I wasn't able to get any useful information. Any guidance would be greatly appreciated. Thanks!
You'll have to use the Queryable.OfType(TResult) extension method in order to filter the entities of type DatabaseProduct or VideoProduct. Look at this sample code
DatabaseProduct dbp = (from d in db.Products.OfType<DatabaseProduct>()
where d.Id == id
select d.FirstOrDefault();
This kind of query will filter the entities of a certain type and so you can act accordingly when you build the list of products (for example redirecting the user to two different details action or something like that)
Have a look here for more info.
Take a look at the Display/Editor Templatesfeature described here: http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-4-custom-object-templates.html
You could try this way:
public ActionResult Details(int id)
{
var product = db.Products.Find(id); // could be a VideoProduct or a DatabaseProduct
if (product == null)
return RedirectToAction("Index");
return View(product.GetType().Name, product);
}
精彩评论