2015-05-26 95 views
2

我的控制器是tStores。 返回所有的商店我的操作方法指數:dropdownlist ASP.NET MVC

// GET: tStores 
public ActionResult Index() 
{ 
    ViewBag.StoreID = new SelectList(db.tStores, "StoreID", "Store_Name"); 
    return View(db.tStores.ToList()); 
} 

在我的索引視圖,我創建了一個下拉列表給我看我店在數據庫中。

@using (Html.BeginForm("Stores","tStores")) 
{ 
    @Html.DropDownList("StoreID",(SelectList)ViewBag.StoreID, "Select Store") 

    <input type="submit" value="submit" /> 

} 

但我不知道如何創建一個存儲的操作方法,將採取從下拉列表參數,然後用STOREID ==返回店裏STOREID,通過下拉列表提供,回索引視圖。

我想我可以做這樣的事情,但它沒有工作:

public ActionResult Stores(int StoreID) 
{ 
    var query = (from s in db.tStores 
       where s.StoreID == StoreID 
       select s).ToList(); 
       return View("Index",query); 
} 
+1

這有什麼做與傳統的ASP。 – Paul

回答

2

問題可能是您正在試圖通過return View("Index",query);傳遞一個查詢,索引方法查詢沒有參數。

我反而建議使用這樣的:

public ActionResult Stores(int StoreID){ 
     var query = (from s in db.tStores 
        where s.StoreID == StoreID 
        select s).ToList(); 
        ViewBag.query = query; 
        return RedirectToAction("Index","Index"); 
} 

現在要使用你的查詢數據時,你只需要輸入ViewBag.query。注意我使用RedirectToAction,因爲如果您只使用return View(),則不會運行ActionResult方法。這可能是你想要的。

+0

索引視圖需要的IEnumerable 所以「公共的ActionResult商店(INT STOREID) { VAR查詢=(從s中db.tStores 其中s.StoreID == STOREID 選擇多個).ToList( ); return View(「Index」,query); } ' 應該返回與tStore中的屬性相同的查詢 – Timur

0

好的,現在它的工作。我必須在店鋪操作方法中加入ViewBag.StoreID = new SelectList(db.tStores, "StoreID", "Store_Name");

public ActionResult Stores(string StoreID) 
      { 
       ViewBag.StoreID = new SelectList(db.tStores, "StoreID", "Store_Name"); 
       var query = (from s in db.tStores 
          where s.StoreID.ToString().Contains(StoreID) 
          select s).ToList(); 

       return View("Index", query); 

} 

public ActionResult Index() 
     { 

      ViewBag.StoreID = new SelectList(db.tStores, "StoreID", "Store_Name"); 
      return View(db.tStores.ToList()); 
     } 

這是我的看法部分:

@using (Html.BeginForm("Stores","tStores")) 
    { 
    @Html.DropDownList("StoreID", ViewBag.StoreID as SelectList) 

     <input type="submit" value="submit" /> 

    }