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

时间:2014-09-22 06:22:57

标签: c# linq lambda asp.net-mvc-5

我想在结果页面上显示状态名称作为标题。在这里,它变得棘手,也许我认为这一切都是错的。

我使用state abbreviation / id值来查询使用ApplicationDbContext的用户,并且该表中存储的状态值是abbr。只(不是名字)。正如您在控制器块中看到的,我正在尝试对我的主db上下文进行新查询以提取状态名称并将其存储在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",无论选择什么。有关我在哪里的任何想法出了问题?

谢谢,

1 个答案:

答案 0 :(得分:0)

您如何在视图中显示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;