如何为模型分配匿名类型?

时间:2012-12-06 19:04:49

标签: c# asp.net asp.net-mvc asp.net-mvc-4 anonymous-types

如何为模型分配匿名类型? 使用ViewBag我可以很容易地分配:

ViewBag.certType = comboType.ToList();

我正从系统中删除所有ViewBags,现在我正在尝试:

model.storeLocations = comboType.ToList();

我收到以下错误:

 Cannot implicitly convert type 'System.Collections.Generic.List<AnonymousType#1>' 
to 'int'    S:\Projects\tgpwebged\tgpwebged\Controllers\AdminController.cs  
376 40  tgpwebged

型号:

public class TipoDocumentoModel
    {
        public sistema_DocType Type { get; set; }
        public IEnumerable<string> Indices { get; set; }
        public IEnumerable<string> NonAssoIndices { get; set; }
        public int storeLocations { get; set; }
    }

控制器:

public ActionResult AdminSettingAddTipo()
    {
        SettingsModels.TipoDocumentoModel model = new SettingsModels.TipoDocumentoModel();

        //Pega os indices e locais de armazenamentos cadastrados no sistema
        using (tgpwebgedEntities context = new tgpwebgedEntities())
        {
            var obj = from u in context.sistema_Indexes select u.idName;
            model.Indices = obj.ToList();

            var comboType = from c in context.sistema_Armazenamento
                            select new
                            {
                                id = c.id,
                                local = c.caminhoRepositorio
                            };

            model.storeLocations = comboType.ToList();
        }

        return PartialView(model);
    }

1 个答案:

答案 0 :(得分:0)

首先,您要尝试将List<>项分配给int媒体资源。

简单的方法从匿名投影中提取出一个命名类。

//model
public List<MyClass> storeLocations { get; set; }

//snip
var comboType = from c in context.sistema_Armazenamento
                select new MyClass
                        {
                            id = c.id,
                            local = c.caminhoRepositorio
                        };

storeLocations = comboType.ToList();

其他选项

  1. 如果您仍想要动态行为,可以将属性更改为dynamic
  2. 投射到Tuple<int, string>()(猜测第二种类型)
  3. 如果最终结果是下拉列表,您可以投射到SelectList()