Laziale
Laziale

Reputation: 8225

Return IEnumerable Model to MVC Controller in MVC4

I'm trying to bind viewmodel to a dataset which comes from json result in MVC. This is what I have:

The function where I'm creating the json result:

private string WsUrl = "https://myUrl";
public List<RestCategories> GetCategoryResults(string api, string site)
{         
    List<RestCategories> categories = new List<RestCategories>();
    RestCategories cat;
    var webRequest = (HttpWebRequest)WebRequest.Create(WsUrl);
    webRequest.Method = "GET";
    try
    {
        var webResponse = (HttpWebResponse)webRequest.GetResponse();
        if ((webResponse.StatusCode == HttpStatusCode.OK) && (webResponse.ContentLength > 0))
        {
            var reader = new StreamReader(webResponse.GetResponseStream());
            string s = reader.ReadToEnd();
            var arr = JsonConvert.DeserializeObject<JArray>(s);
            int i = 1;               

            foreach (JObject obj in arr)
            {
                cat = new RestCategories();
                cat.DisplayInPrimaryCategoryListing = (bool)obj["DisplayInPrimaryCategoryListing"];
                cat.ID = (int)obj["ID"];
                cat.ItemCount = (int)obj["ItemCount"];
                cat.Name = (string)obj["Name"];
                cat.Order = (int)obj["Order"];
                cat.SubCategoryOf = (string)obj["SubCategoryOf"].ToString(); 
                categories.Add(cat);
            }
            return categories;
        }
    }
    catch
    {
        throw;
    }
    return categories;
}

This is what I have for CategoriewViewModel:

public class CategoriesViewModel
    {
        public IEnumerable<RestCategories> Categories;
    }

RestCategories definition:

public class RestCategories
    {           
        public int ID { get; set; }
        public int ItemCount { get; set; }
        public string Name { get; set; }            
    }

And finally in the controller I want to make something like this:

[HttpGet]
public ActionResult Categories()
{            
    MyModel modelApi = new MyModel();
    List<RestCategories> itemsResult = modelApi.GetCategoryResults("test", "test");
    CategoriesViewModel modelCat = new CategoriesViewModel
    {
        //I need some magic here to return ienumerable dataset of RestCategories
        Categories = itemsResult.                                   
    };
    return View(modelCat);
}

Now, as you can see I want to return IEnumerable type of model, since I'll have multiple results from the web service call. Maybe I need to do the GetCategoryResults method to return multiple results? Even if I do that how can I then look through the returned object in the controller to get what I want?

Upvotes: 0

Views: 11306

Answers (1)

PlTaylor
PlTaylor

Reputation: 7545

List inherits IEnumerable. You should be able to just change your itemsResult variable to IEnumerable and have everything be happy.

[HttpGet]
public ActionResult Categories()
{            
    MyModel modelApi = new MyModel();
    IEnumerable<RestCategories> itemsResult = modelApi.GetCategoryResults("test", "test");
    CategoriesViewModel modelCat = new CategoriesViewModel
    {
        Categories = itemsResult                                  
    };
    return View(modelCat);
}

as a side note I prefer using var when possible as it avoids these problems in the first place. For example

[HttpGet]
public ActionResult Categories()
{            
    var modelApi = new MyModel();
    var itemsResult = modelApi.GetCategoryResults("test", "test");
    var modelCat = new CategoriesViewModel
    {
        Categories = itemsResult                                
    };
    return View(modelCat);
}

This code is simple, concise and if you change the types of the variables in the future it is less brittle than strongly typing it. Ultimately this is a matter of style and preference.

Upvotes: 3

Related Questions