美国各州下拉列表-需要显示州名称标题

本文关键字:显示 标题 下拉列表 美国 | 更新日期: 2023-09-27 18:23:47

我想在结果页面上将状态名称显示为标题。这就是它变得棘手的地方,也许我做错了。

我使用状态缩写/id值来查询使用ApplicationDbContext的用户,并且存储在该表中的状态值仅为缩写(而不是名称)。正如您在下面的控制器块中看到的那样,我正在尝试对我的主数据库上下文进行新的查询,以提取状态名称并将其存储在viewbag中。

当你选择一个状态并输入它时,一切都会正常工作,但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",无论选择什么。有什么想法吗?

谢谢,

美国各州下拉列表-需要显示州名称标题

如何在视图中显示ViewBag对象?您还必须记住,查询返回的是OBJECT,而不是对象的单个属性。应该是:

 var _nameOfState = db.StateOrProvinces.Where(n => n.StateAbbr == id).State;

其中"State"是完整的州名称列。

此外,检索单个记录时,应使用"single"、"SingleOrDefault"或"Find"(如果param是主键)var _nameOfState = db.StateOrProvinces.Single(n => n.StateAbbr == id).State