Asp.Net MVC dropdown

Hello Experts,

I am learning MVC so please help me.

I am using Entity Framework for CRUD operation.

When I generate Controller/ View for Products, it creates Index/ Edit/ Details/ Delete view.

What I need is, in Create View, it creates only one dropdown for "SubCategory", instead I want to have "Category" Dropdown
and after its selection "SubCategory" dropdown.

Your help is appreciated. Thanks
dbpng.png
LVL 8
Johny BravoAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Miguel OzSoftware EngineerCommented:
To build a dropdown manually just assign your new select list( filled with your table contents) to ViewBag.Categories as follows:
1) Add the following code to your view:
@Html.Label("Product Category")
@Html.DropDownList("ProductCategories", ViewBag.Categories as SelectList)

Open in new window


2) Add the following code to your controller create method:
var categories = _dbContext.Set<ProductCategory>();
ViewBag.Categories = new SelectList(categories, "ProductCategoryID", "Name");

Open in new window


Notes: 1) ProductCategory is your EF class that maps Category table.
2)  If more help needed, please post create view and controller method.
0
Johny BravoAuthor Commented:
View / Model / Controller are attached.

Please check
Create.txt
ProductsController.txt
Product.txt
0
Johny BravoAuthor Commented:
Ok now what I've done,

      <div class="editor-label">
            @Html.LabelFor(model => model.CategoryId, "Category")
        </div>
        <div class="editor-field">
            @Html.DropDownList("CategoryId", String.Empty)
            @Html.ValidationMessageFor(model => model.CategoryId)

        </div>

and in controller,
   ViewBag.CategoryId = new SelectList(db.Categories, "CategoryId", "CategoryName");

so it creates a Category dropdown, but I need subcategory dropdown to be filled based on the selection of Category.

>>Moving from Asp.Net to MVC is a bit difficult :)
>>As in Asp.Net, we could have AutoPostBack="true" and fill the Subcategory ddl.
0
Miguel OzSoftware EngineerCommented:
For server based solution, you need to create a ProductViewModel class in your Model folder.
This new class will contain all your product public properties +  a property called CategoryId.
public class ProductViewModel
{
	public int CategoryId { get; set; }
	
	public int SubCategoryId { get; set; }
	public int ProductId { get; set; }
	public string ProductName { get; set; }
	//All other required properties goes here.
	
	//helper methods to map to/from Product
	public Product ToProduct()
	{
	    result = new Product();
	    result.ProductId = this.ProductId; //For create will be empty
	    result.ProductName = this.ProductName;
	    //todo map other properties here.
	}
	public void AssignFromProduct(Product p)
	{
	    this.ProductId = p.ProductId; //For create will be empty
	    this.ProductName = p.ProductName;
	    //todo map other properties here.
	}
}

Open in new window

Then your controller methods will look like:
//
// GET: /AdminPanel/Products/Create

public ActionResult Create()
{
    var categories = db.Set<ProductCategory>(); //Assumption: categories are stored/mapped in ProductCategory class
    ViewBag.Categories = new SelectList(categories, "ProductCategoryID", "Name");
    ViewBag.SubCategoryId = new SelectList(db.SubCategories, "SubCategoryId", "SubCategoryName");
    ViewBag.VendorId = new SelectList(db.Vendors, "VendorId", "VendorName");
    return View();
}

//
// POST: /AdminPanel/Products/Create

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(ProductViewModel productvm)
{
    if (ModelState.IsValid)
    {
	product = productvm.ToProduct()
	db.Products.Add(product);
	db.SaveChanges();
	return RedirectToAction("Index");
    }

    var categories = db.Set<ProductCategory>(); //Assumption: categories are stored/mapped in ProductCategory class
    ViewBag.Categories = new SelectList(categories, "ProductCategoryID", "Name", productvm.CategoryId);
    ViewBag.SubCategoryId = new SelectList(db.SubCategories, "SubCategoryId", "SubCategoryName", productvm.SubCategoryId);
    ViewBag.VendorId = new SelectList(db.Vendors, "VendorId", "VendorName", productvm.VendorId);
    return View(productvm);
}

Open in new window

and your model must use this new class: (replace  Product with ProductViewModel)
@model MVCCart.Models.ProductViewModel
Last but not least you need to add the category dropdown list:
@Html.Label("Product Category")
@Html.DropDownList("ProductCategories", ViewBag.Categories as SelectList, new { onchange = "this.form.submit();" })

Notice that I implement onchange event because MVC dropdowns do not post back by default.
The trick is to add all your required information in this helper class so that MVC knows how to map the information.

Note: There are other javascript based solutions using Jquery and AJAX that you may consider in the future.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.