我正在尝试通过视图模型在视图中显示从linq查询检索到的数据。我为linq查询设置了一个变量,然后在视图模型的表实例中引用了它。如果我放弃了视图模型而只在返回视图中返回了变量,那么我将获得所需的数据。当我尝试使用视图模型时,当我引用linq查询变量时,我不得不调用ToString,而不是我想要的结果数据,而是得到此TRAIntranet2019.Models.TblShiftInfo,这就是我要查询的表。而且,我正在为视图模型(使用视图模型时)或常规模型(仅使用linq变量)更改视图顶部的模型引用。 Shift target是我正在研究的当前示例。
private TRAKERContext db = new TRAKERContext();
// GET: LandingPageVMs
public IActionResult Index()
{
var shiftTarget = db.TblShiftInfo.FirstOrDefault();
//var rvuvalue = db.Tradetail.FirstOrDefault().ToString();
TblShiftByRadByDate tblShiftByRadByDate = new TblShiftByRadByDate()
{
//ShiftName = "Late Night Shift"
};
Tradetail tradetail = new Tradetail()
{
//Rvuvalue = (double)rvuvalue
//SignLastName = rvuvalue.ToString()
};
TblShiftInfo tblShiftInfo = new TblShiftInfo()
{
//ShiftAvgTarget = Convert.ToDouble(shiftTarget),
Shift_Name = shiftTarget.ToString()
};
RadidCrosswalk radidCrosswalk = new RadidCrosswalk()
{
RadFname = "Jimmie"
};
FacilityCrosswalk facilityCrosswalk = new FacilityCrosswalk()
{
FacilityName = "TRA"
};
LandingPageVM vm = new LandingPageVM()
{
TblShiftByRadByDate = tblShiftByRadByDate,
Tradetail = tradetail,
TblShiftInfo = tblShiftInfo,
RadidCrosswalk = radidCrosswalk,
FacilityCrosswalk = facilityCrosswalk
};
return View(vm);
}
预期输出=“班次名称”
实际输出=“ TRAIntranet2019.Models.TblShiftInfo”
答案 0 :(得分:1)
我不明白这个问题,但想弄清楚...
对控制器的操作:
public IActionResult About()
{
TblShiftInfo tblShiftInfo = new TblShiftInfo()
{
Shift_Name = "Shift Name Example",
ShiftAvgTarget = 12345
};
LandingPageVM vm = new LandingPageVM()
{
TblShiftInfo = tblShiftInfo,
};
return View(vm);
}
视图:
@model MyWevApp2.Models.LandingPageVM
<h2>Data in ViewModel</h2>
<p>@Model.TblShiftInfo.Shift_Name</p>
<p>@Model.TblShiftInfo.ShiftAvgTarget</p>
如果您不想使用ViewModel ...,则可以使用ViewBag或ViewData。例如:
控制器:
public IActionResult Contact()
{
TblShiftInfo tblShiftInfo = new TblShiftInfo()
{
Shift_Name = "Shift Name Example",
ShiftAvgTarget = 12345
};
ViewBag.TblShiftInfo = tblShiftInfo;
return View();
}
在视图中,您可以使用ViewBag:
<p>@ViewBag.TblShiftInfo.Shift_Name</p>
希望有帮助!