backtrack
backtrack

Reputation: 8154

How to handle a List, Collection or IEnumerable in View

Hi all can anyone help me ... Im very new to c# and mvc

The Model is:

public class CatagoryModel {
    public int Id { get; set; }
    public string  CName { get; set; }
}

The Controller is:

   public ActionResult catagory() {
        var c = new CatagoryModel();
        var URL="";

        HttpWebRequest req = WebRequest.Create(URL)
                   as HttpWebRequest;
        string result = null;
        using (HttpWebResponse resp = req.GetResponse()
                                      as HttpWebResponse)
        {
            StreamReader reader =
                new StreamReader(resp.GetResponseStream());
            result = reader.ReadToEnd();
        }


        var categories = JsonConvert.DeserializeObject<List<CatagoryModel>>(result);

        return View(categories);
      }

The View like this

@model MvcApplication1.Models.CatagoryModel
<ul>
@foreach(var k in Model){
   <li>@k.Id</li> 
    <li>@k.CName</li>

}

And i dont know what went wrong ...
It shows an error while rendering the view ..

Upvotes: 4

Views: 883

Answers (2)

Kevin Brechb&#252;hl
Kevin Brechb&#252;hl

Reputation: 4727

Your Model is a list of CategoryModel, not a single CategoryModel:

@model IEnumerable<MvcApplication1.Models.CatagoryModel>

Upvotes: 0

Rapha&#235;l Althaus
Rapha&#235;l Althaus

Reputation: 60503

Well, if your model is Enumerable, in your view, it must be enumerable !

@model IEnumerable<MvcApplication1.Models.CatagoryModel>

Upvotes: 5

Related Questions