Timur
Timur

Reputation: 131

dropdownlist ASP.NET MVC

My controller is tStores. I have action method Index that returns all stores:

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

In my Index view, I've created a dropdownlist to show me stores I have in the database.

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

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

}

But I do not know how to create a Stores action method that would take parameter from dropdownlist and then return the store with StoreID == to StoreID, provided via dropdownlist, back to the Index view.

I thought I could do something like this, but it did not work:

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

Upvotes: 2

Views: 86

Answers (2)

Timur
Timur

Reputation: 131

Ok, Now it works. I had to put ViewBag.StoreID = new SelectList(db.tStores, "StoreID", "Store_Name"); in Stores action method.

    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());
        }

And this is my view part:

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

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

    }

Upvotes: 0

aLarsson
aLarsson

Reputation: 91

The problem may be that you are trying to pass a query through return View("Index",query);, and your Index method has no parameters for query.

I would instead suggest using it like this:

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");
}

And now where you want to use the data in your query you would just type ViewBag.query. Note I use RedirectToAction because if you just use return View() no ActionResult method will run. Which is probably what you want.

Upvotes: 2

Related Questions