【发布时间】:2023-03-27 16:30:01
【问题描述】:
我想在结果页上显示州名作为标题。这就是它变得棘手的地方,也许我做错了。
我正在使用状态缩写/id 值来查询使用 ApplicationDbContext 的用户,并且存储在该表中的状态值是缩写。只有(不是名字)。正如您在下面的控制器块中看到的那样,我正在尝试对我的主数据库上下文进行新查询以提取状态名称并将其存储在视图包中。
当您选择一个状态并输入它时,一切都会正常运行,但 ViewBag.NameOfState 会显示:
SELECT [Extent1].[Id] AS [Id], [Extent1].[StateAbbr] AS [StateAbbr], [Extent1].[StateName] AS [StateName] FROM [dbo].[StateOrProvinces] AS [Extent1] WHERE ([Extent1].[StateAbbr] = @p__linq__0) OR (([Extent1].[StateAbbr] IS NULL) AND (@p__linq__0 IS NULL))
Controller:
public ActionResult ShopsUS(string id)
{
ApplicationDbContext ShopDB = new ApplicationDbContext();
var stateList = ShopDB.Users.Where(s => s.State == id).OrderBy(s => s.City);
//Second db query to get the state name for header display
if (stateList != null)
{
CatalogDb db = new CatalogDb();
var _nameOfState = db.StateOrProvinces.Where(n => n.StateAbbr == id);
ViewBag.NameOfState = _nameOfState;
}
return View(stateList.ToList());
}
Controller Using LINQ instead:
public ActionResult ShopsUS(string id)
{
ApplicationDbContext ShopDB = new ApplicationDbContext();
var stateList = ShopDB.Users.Where(s => s.State == id).OrderBy(s => s.City);
if (stateList != null)
{
CatalogDb db = new CatalogDb();
var name = from n in db.StateOrProvinces
where n.StateAbbr == id
select n.StateName;
ViewBag.NameOfState = name;
}
return View(stateList.ToList());
}
该值作为字符串传递并与传入控制器的 id 匹配(id:“AL”、“AK”,无论选择什么。有什么想法我哪里出错了吗?
谢谢,
【问题讨论】:
标签: c# linq lambda asp.net-mvc-5