1

I am new in learning asp.net MVC and am trying to access some data from the controller in my view. This is my code:

public ActionResult Index(string subcategory)
{
    List<Object> products = db.ListOfProducts(subcategory);

    return View(products);
}

I know that after passing the LIST into the VIEW there should be some way to acces the data in the VIEW but I can't seem to figure out how. Normally when I create a view based on a model I know that by using the model object I can acces the data I need, but usually theres a definiton on the top regarding the model and in my caase there is none.

So how can I acces the LISTS data in my view?

Paul Fleming
  • 24,238
  • 8
  • 76
  • 113
Nistor Alexandru
  • 5,309
  • 9
  • 46
  • 71
  • You can look at this where the data is bound to a web grid : http://stackoverflow.com/questions/11351853/mvc-3-populate-bind-webgrid-form-ajax – Praveen Dec 24 '12 at 14:41

3 Answers3

2

Add this to the top of your view to define the model type:

@model List<Object>

You may need to namespace this as either:

@using Systems.Collections.Generic;
@model List<Object>

or

@model Systems.Collections.Generic.List<Object>
Paul Fleming
  • 24,238
  • 8
  • 76
  • 113
1

Yes, just create a strong type view by adding to your view

 @model IList<Products>

after that you can iterate throw you model like this:

@foreach(var prod in Model)
{
   //...
}
CoffeeCode
  • 4,296
  • 9
  • 40
  • 55
1

You should have a corrosponding view in your Views folder called Index (in a sub-folder that matches your controller name - so if you controller is called HomeController you will need a 'Home' folder underneath the views folder) If you don't already have a view you can create one by right-clicking on the folder and clicking 'Add view'.

Ensure you have a statement at the top of the view which reads:

@model Systems.Collections.Generic.List<object>

You should now be able to access your data via the Model property of your view.

Benjamin Gale
  • 12,977
  • 6
  • 62
  • 100