【问题标题】:US States Drop Down List - need State Name Header to Show美国各州下拉列表 - 需要显示州名称标题
【发布时间】: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


    【解决方案1】:

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

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

    其中“州”是完整州名的列。

    另外,当检索单个记录时,您应该使用“Single”、“SingleOrDefault”或“Find”(如果参数是主键) var _nameOfState = db.StateOrProvinces.Single(n => n.StateAbbr == id).State;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-20
      • 2015-09-18
      • 1970-01-01
      • 2010-11-17
      • 2011-08-09
      • 2021-08-22
      • 1970-01-01
      相关资源
      最近更新 更多