0
votes

I have two DropDownList which are related to each other by a foreign key. Category and Subcategory(with categoryid as foreign key). I am retrieving Categories from database and filling them up as: DB CLASS

public class DB
 {
     public static List<SelectListItem> Categories {
              get{
                   List<SelectListItem> list = new List<SelectListItem {
                    new SelectListItem{Text = "Category1" , Value = "categoryId1"},
                    new SelectListItem{Text = "Category2" , Value = "categoryId2"}
                 };
        return list;
     }
    public static List<SelectListItem> SubcategoryWithCategoryId(int categoryId)
    {...}
 }

Now i can fill Subcategory dropdown with a method which expects categoryId as input:
View

 @Html.DropDownList("Category", DB.Categories, "Select Category", new { style = "width:80px" })

 @Html.DropDownList("Subcategory", DB.SubcategoryWithCategoryId(categoryId), "Select Subcategory", new { style = "width:80px" })

I am a beginner in ASP.NET MVC and i am using ADO.NET to access the database. How can i now get the Selected Item's Value Field so i can fit it into my DB.SubcategoryWithCategoryId(categoryId) to retrieve subcategories mapped across the selected category?

Controller

public ActionResult Index()
        {
            return View();
        }
1
add your code about controller and your view tooHien Nguyen
@HienNguyen Okay i have edited my question..Blank Blank
In which method you would like to do your update operation based on your selected value against you database, can you show it?Salah Akbari
@SalahAkbari For now i just want when i select value in categories dropdown the subcategories dropdown gets filled.Blank Blank
What happens if you change @Html.DropDownList("Category" to @Html.DropDownList("CategoryId"? They need to be same in order Model Binder works as expected,Salah Akbari

1 Answers

1
votes

You need handle onchange of dropdown as

 @Html.DropDownList("Category", DB.Categories, "Select Category", new { style = "width:80px", 
onchange = "location.href='@Url.Action("Index", "Controller", new { category= "yourcategory"})'" })

And add category as paramter of index action

public ActionResult Index(string category)