2014-09-22 67 views
0

我想在结果页面上显示状态名称作为标题。这就是棘手的地方,也许我会说这一切都是错误的。美国各州下拉列表 - 需要状态名称标题显示

我正在使用状态缩写/ id值来查询使用ApplicationDbContext的用户,并且该表中存储的状态值是abbr。只(不是名字)。正如你可以在控制器块中看到的,我正在尝试对我的主数据库上下文进行一次新的查询,以获取状态名称并将其存储在一个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”,无论选择在哪里我已经错了有什么想法

感谢,

回答

0

你是如何在你的视图中显示的ViewBag对象上,还必须保持记住你的查询是返回一个对象,而不是一个单一的道具物体的特性。它应该是:

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

其中“状态”是完整状态名称的列。

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