3

我正在尝试查询数据库并将这些结果存储在模型中,其中一列是数字,一列是字符串数据:

模型:

using System.Data.Entity;

namespace Portal.Models
{
    public class CompanyListId
    {
        public int Id { get; set; }
        public string CompanyName { get; set; }
    }

    public class CompanyListIdDbContext : DbContext
    {
        public DbSet<CompanyListId> Contacts { get; set; }
    }
}

控制器:

    public PartialViewResult SelectCompanyFromDropdown()
            {
                using (var dc = new CompanyListIdDbContext())
                {
                    var content = from p in db.Companies
                                    select new { p.CoId, p.CompanyName };
                }
//I want to set Models ID = to each instance of coid
            //Set Models CompanyName to each instance of companyname

                return PartialView();

            }

我不知道从哪里开始,我正试图从这个模型中下拉。

我将代码块更新为:

public PartialViewResult SelectCompanyFromDropdown()
        {
            using (var dc = new CompanyListIdDbContext())
            {
                var content = from p in db.Companies
                    select new CompanyListId
                    {
                        Id = p.CoId,
                        CompanyName = p.CompanyName
                    };
                return PartialView(content.ToList());//giving an error
            }
        }

我的观点是:

@model Portal.Models.CompanyListId

@Html.DropDownListFor(m => m.CompanyName, Model.CompanyName)

这似乎也不起作用,我需要从我认为的操作中返回我的模型,这样视图才能正确使用数据。

4

2 回答 2

9

您应该将结果投影到您的班级CompanyListId

var content = from p in db.Companies
              select new CompanyListId
                  { 
                    Id = p.CoId, 
                    CompanyName  = p.CompanyName 
                  };

编辑:

我不确定错误,但您可以尝试:

public PartialViewResult SelectCompanyFromDropdown()
{
    List<CompanyListId> content = null;
    using (var dc = new CompanyListIdDbContext())
    {
        content = (from p in db.Companies
            select new CompanyListId
            {
                Id = p.CoId,
                CompanyName = p.CompanyName
            }).ToList();
    }
    return PartialView(content);
}
于 2013-10-02T19:41:03.750 回答
3

你可以像这样选择你的类的一个新实例:

var content = from p in db.Companies
              select new CompanyListId 
              { 
                  Id = p.CoId, 
                  CompanyName = p.CompanyName 
              };
于 2013-10-02T19:40:50.377 回答