I am having problems passing a ViewModel into a view.
My ViewModel:
namespace ImpactDBASPNet.Models
{
public class ComputerInfoViewModel
{
public List<string> CompanyList { get; set; }
public tbl_computerinfo entitymodeleffort { get; set; }
}
}
Controller:
public ActionResult Index()
{
var tbl_computerinfo = db.tbl_computerinfo.Include(t => t.tbl_equipment);
tbl_computerinfo = tbl_computerinfo.Where(c => c.Company == "Test Company");
List<string> companylist = new List<string>();
companylist.Add("Hello1");
companylist.Add("hello2");
ComputerInfoViewModel model = new ComputerInfoViewModel();
model.CompanyList = companylist;
model.entitymodeleffort = tbl_computerinfo;
return View(model);
}
I'm doing this primarily because I need to pass a list for a dropdownlist in my view, so I need to pass in the entity framework model AND the list. The error I am getting is:
Error 1 Cannot implicitly convert type 'System.Linq.IQueryable<ImpactDBASPNet.Models.tbl_computerinfo>' to 'ImpactDBASPNet.Models.tbl_computerinfo'. An explicit conversion exists (are you missing a cast?) c:\impactdbaspnet\controllers\tbl_computerinfocontroller.cs 31 39 ImpactPortal
Property entitymodeleffort
is typeof tbl_computerinfo
but you assigning IEnumerable<tbl_computerinfo>
to it, resulting in the error. You need to use FirstOrDefault()
(or one of the variants - Single()
etc.) that returns a single tbl_computerinfo
object.
Change the code to
public ActionResult Index()
{
var tbl_computerinfo = db.tbl_computerinfo
.Include(t => t.tbl_equipment)
.Where(c => c.Company == "Test Company")
.FirstOrDefault();
List<string> companylist = new List<string>() { "Hello1", "Hello2" }; // save a few lines of code
ComputerInfoViewModel model = new ComputerInfoViewModel();
model.CompanyList = companylist;
model.entitymodeleffort = tbl_computerinfo;
return View(model);
}
Side note: Since companylist
is used for a dropdownlist
, you can make the property SelectList
public SelectList CompanyList { get; set; }
and
model.CompanyList = new SelectList(companylist);
and in the view
@Html.DropDownListFor(m => m.entitymodeleffort.SomeProperty, Model.CompanyList, ...)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.