I'm trying to build a generic grid view in an ASP.NET MVC application.
Let me explain with some code:
public interface ITrustGrid<T>
{
IPagedList<T> Elements { get; set; }
IList<IColumn<T>> Columns { get; set; }
IList<string> Headers { get; }
}
This is an interface of a class that allows me to set columns and expressions in my controller.
I pass implementations to a partial view like this:
<% Html.RenderPartial("SimpleTrustGridViewer", ViewData["employeeGrid"] as TrustGrid<EmployeeInfoDTO>); %>
The problem is that I can't figure out how to make the partial view that renders the grid generic.
In other words, I want to turn this:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<ITrustGrid<EmployeeInfoDTO>>" %>
into something like this:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<ITrustGrid<T>>" %>
=> How can I make my partial view generic in the most simple way?
EDIT:
I solved this by using a TrustGridBuilder that has a public TrustGrid GetTrustGrid() method which returns a non-generic TrustGrid. The TrustGrid contains strings instead of linq stuff. So I execute the linq in the GetTrustGrid() method and put the strings in a TrustGrid object.
Thanks for everybody to help me on the right track.
Partial Views can use the Page Model for their data whereas Child Actions use independent data from the Controller. Editor/Display templates pass items from the model to the system but can be overridden by user partial views.
It helps us to reduce code duplication. In other word a partial view enables us to render a view within the parent view. The partial view is instantiated with its own copy of a ViewDataDictionary object which is available with the parent view so that partial view can access the data of the parent view.
You could make all your model types that you would pass into this partial inherit from a base class/interface that establishes the basic behavior that would be used by this partial view and accept any object of that class/interface type, or just have the view accept any type of object and then use reflection to base your partial view behavior off of.
EXAMPLE:
public interface IDisplayModel
{
string DisplayText{get;set;}
string ImageUrl{get;set;}
string AltText{get;set;}
}
public interface ITrustGrid<T> where T : IDisplayModel
{
IPagedList<T> Elements { get; set; }
IList<IColumn<T>> Columns { get; set; }
IList<string> Headers { get; }
}
<%@ Control Language="C#"
Inherits="System.Web.Mvc.ViewUserControl<ITrustGrid<IDisplayModel>>" %>
Naturally, your IDisplayModel
would vary based on your desired behavior. This would then allow you to pass in anything to this partial that implements this base interface to establish general behavior.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With