3

Possible Duplicate:
Generic partial view: how to set a generic class as model?

I am trying to build common functionality using generic types but got stuck with below scenario.

View Model

public class DeleteForm<T>  
{
    public LogInfo Ticket { get; set; }
    public string Id { get; set; }

    public DeleteForm() {
      Ticket = new LogInfo();
    }

    public DeleteForm(T viewModel) : this() {
      ViewModel = viewModel;
    }

    public T ViewModel { get; set; }
}

Controller

public ActionResult Index(string name)
{
   return View("index", new DeleteForm<List<Users>>(new List<Users>());
}

List Screen

@model DeleteForm<List<Users>>
//gridview displays list of users
@Html.Partial("revisionwindow", Model)

Partial View

@model DeleteForm<T> <---Its not working

@Html.EditorFor(o=>o.Ticket)
@Html.EditorFor(o=>o.Id)
Community
  • 1
  • 1
Nikhil
  • 33
  • 1
  • 3
  • I tried by passing object and dynamic but it doesn't seem to work. For ex: @Html.Partial("revisionwindow", (object) Model) but in the partial view, I am unable to cast it back to the DeleteForm. – Nikhil Oct 18 '12 at 19:11
  • I tried by using interface too but in the posted link interface contains independent properties. But in my case, I need to initialize the list based on a specific type i.e., T. – Nikhil Oct 18 '12 at 19:15

2 Answers2

6

use dynamic model instead. your partial view can look something like this :

@model dynamic

 @{
      var myModel = (DeleteForm<List<Users>>) Model;
 }

@Html.EditorFor(o=>myModel.Ticket)
@Html.EditorFor(o=>myModel.Id)

hope this help.

Behnam Esmaili
  • 5,835
  • 6
  • 32
  • 63
  • I am trying to replace List with generic type so that it will be common across all modules. T can be list or other custom view model which contains the list. So var myModel = (DeleteForm>) Model, doesn't work in my case. Instead it should be (DeleteForm) Model; which is giving error. – Nikhil Oct 18 '12 at 19:14
1

If you pass a model to view, it has to be strongly-typed (particular type). So SomeClass<T> type won't work. Instead of generic type a base class could fill your requirements. What I mean is: View Model

public abstract class Form
{
    public Form()
    {
        Ticket = new LogInfo();
    }
    public LogInfo Ticket {get; set;}
    public int Id {get; set;}
}
public class DeleteUsersForm: Form
{
    public DeleteUsersForm(IEnumerable<Users> users):base()
    {
        this.ViewModel = users;
    }

    public IEnumerable<Users> ViewModel {get; set;}
}

Controller

public ActionResult Index(string name)
{
    return View(new DeleteUsersForm(new List<Users>()));
}

List Screen

@model DeleteUsersForm
//displays list
@Html.Partial("revisionwindow", Model)

Partial View

@model Form

@Html.EditorFor(o=>o.Ticket)
@Html.EditorFor(o=>o.Id)
BenMorel
  • 34,448
  • 50
  • 182
  • 322
Miron
  • 171
  • 2