【问题标题】:Return IEnumerable Model to MVC Controller in MVC4在 MVC4 中将 IEnumerable 模型返回给 MVC 控制器
【发布时间】:2026-01-29 18:50:01
【问题描述】:

我正在尝试将视图模型绑定到来自 MVC 中的 json 结果的数据集。 这就是我所拥有的:

我正在创建 json 结果的函数:

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;
}

这就是我对CategoriewViewModel 的要求:

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

RestCategories 定义:

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

最后在控制器中我想做这样的事情:

[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);
}

现在,如您所见,我想返回 IEnumerable 类型的模型,因为我会从 Web 服务调用中获得多个结果。也许我需要做GetCategoryResults 方法来返回多个结果?即使我这样做了,我如何才能查看控制器中返回的对象以获得我想要的东西?

【问题讨论】:

  • 不 List 实现 IEnumerable 接口?还是我在您的问题中遗漏了什么?
  • @davidmartensson 所有列表都实现了 IEnumerable 接口。
  • @laziale 你的问题不清楚。你到底想要什么?您的控制器 Categories() 操作已经在调用 GetCategoryResults() 函数,获取 List 结果并将其放置在模型 Categories 属性中。一切看起来都很好,那么您还需要什么? “我如何才能查看控制器中返回的对象”是什么意思?它是一个 List,因此您可以使用 foreach 来遍历它,例如。
  • @BartoszKP 这是一个假设,尽管它很可能是正确的。

标签: c# asp.net asp.net-mvc json asp.net-mvc-4


【解决方案1】:

List 继承 IEnumerable。您应该能够将 itemsResult 变量更改为 IEnumerable 并让一切都开心。

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

作为旁注,我更喜欢在可能的情况下使用 var,因为它首先避免了这些问题。例如

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

此代码简单、简洁,如果您将来更改变量的类型,它比强输入它更易碎。归根结底,这是风格和偏好的问题。

【讨论】:

  • 有时 MVC 可能比我想象的要简单得多。感谢您的帮助
  • 没问题....有时你需要自己想办法才能看到解决方案。
  • @Laziale MVC 在这里无关紧要。
最近更新 更多