2013-04-10 4 views
2

Моя цель: Реализация сетки с частичным представлением. поэтому я создал класс для сеткиОбщий вид во взглядах

Мой код

public class HomeController : Base_Controller 
{ 
    // 
    // GET: /Home/ 

    public ActionResult Index() 
    { 
     // return View("~/Views/Home/User/Login"); 
     if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated) 
     { 
      var users = UserBL.GetAllUsers(); 
      Type type = users.FirstOrDefault().GetType(); 
      Models.Grid<DAL.Entities.User_Details> grid = new Models.Grid<DAL.Entities.User_Details>(users); 

      ViewBag.GridData = grid; 
      return View(); 
     } 
     else 
     { 
      return RedirectToAction("Login", "User"); 
     } 

     // return "Hellow"; 
    } 
} 

и моей сетки класса является

public class Grid<T> 
{ 
    public Grid(object datasource) 
    { 

     Data = (List<T>)datasource; 

    } 

    public Grid() 
    { 

    } 
    public List<T> Data 
    { 
     get; 
     set; 
    } 


    public IEnumerable<System.Reflection.PropertyInfo> Props 
    { 
     get 
     { 
      return typeof(T).GetProperties().AsEnumerable(); 
     } 

    } 
} 

мой взгляд Кодекс

@using DAL.Entities; 
@{ 
    ViewBag.Title = "Index"; 
} 

<h1>welcome User....!</h1> 
@{Models.Grid<User_Details> modelgrid = (Models.Grid<User_Details>)@ViewBag.GridData;} 

@Html.Partial("GridView",modelgrid) 

Мой Частичный вид это. в этом коде первая строка здесь, я хочу использовать любой механизм отражения. может любой один изменить код, работоспособный код

@model AC.Models.Grid<Need a solution here> 

@if (Model != null) 
{ 
    <table> 
     <thead> 
      <tr> 
       @foreach (var col in Model.Props) 
       { 

       <td>@Html.Display(col.Name)</td> 

      } 
     </tr> 
    </thead> 
    <tbody> 
     @foreach (var item in Model.Data) 
     { 
      <tr> 
       @foreach (var prop in Model.Props) 
       { 
        <td>@Html.Display(prop.GetValue(item, null).ToString())</td> 
       } 
      </tr> 
     } 
    </tbody> 



</table> 

}

ответ

3

Поскольку вы уже используете отражение там не так много преимуществ использования дженериков здесь. Как насчет:

public class Grid 
{ 
    private readonly Type type; 
    public Grid(IEnumerable datasource) 
    { 
     if (datasource == null)   
     { 
      throw new ArgumentNullException("datasource"); 
     } 

     this.type = datasource.GetType().GetGenericArguments().SingleOrDefault(); 

     if (this.type == null) 
     { 
      throw new ArgumentException("The datasource must be generic"); 
     } 

     this.Data = datasource; 
    } 

    public IEnumerable Data { get; private set; } 

    public IEnumerable<System.Reflection.PropertyInfo> Props 
    { 
     get 
     { 
      return this.type.GetProperties().AsEnumerable(); 
     } 
    } 
} 

, а затем:

@model AC.Models.Grid 

@if (Model != null) 
{ 
    <table> 
     <thead> 
      <tr> 
       @foreach (var col in Model.Props) 
       { 
        <td>@Html.Display(col.Name)</td> 
       } 
      </tr> 
     </thead> 
     <tbody> 
      @foreach (var item in Model.Data) 
      { 
       <tr> 
        @foreach (var prop in Model.Props) 
        { 
         <td>@Html.Display(prop.GetValue(item, null).ToString())</td> 
        } 
       </tr> 
      } 
     </tbody> 
    </table> 
} 
+0

IEnumarable является интерфейс правильно. ему нужен IEnumarable . предположим, что u изменил его на Enumarable. то как мы можем получить свойства с возвращаемым типом (T) .GetProperties(). AsEnumerable(); и как мы назначим данные для списка для Enumarable – Kartheek

+0

Я обновил свой ответ, чтобы проиллюстрировать концепцию. –

+0

Ошибка \t Использование универсального типа 'System.Collections.Generic.IEnumerable ' требует 1 аргумента типа – Kartheek

Смежные вопросы