Amazon Ad

Monday 21 April 2014

Creating Dependent DropDownList in MVC without jQuery.



Hi Guys,

I was given a task to generate dependent values in DropDownList without using jQuery. However this approach is not recommended but incase you still want to generate the dependent dropdownlist values based upon the parent dropdownlist value, Here are the steps to do so.

In my example i am using an example of Category, SubCategory and Product. Based on the category dropdown, subcategory dropdown list is generated and the product is then saved based on the category and subcategory values. In this example i have taken both category and subcategory reference in product table, However it can be done by taking only reference of subcategory table.

Step 1: Generate models
public class Category
    {
        [Key]
        public virtual int CategoryId { get; set; }
        public virtual string CategoryName { get; set; }
        public List<SubCategory> SubCategories { get; set; }
        public List<Product> Products { get; set; }
    }



public class SubCategory
    {
        [Key]
        public virtual int SubCategoryId { get; set; }
        public virtual string SubCategoryName { get; set; }
        public int CategoryId { get; set; }
        public virtual Category Category { get; set; }
        public virtual List<Product> Products { get; set; }
    }
 public class Product
    {
        [Key]
        public virtual int ProductId { get; set; }
        public virtual string ProductName { get; set; }
        public int CategoryId { get; set; }
        public virtual Category Category { get; set; }
        public int SubCategoryId { get; set; }
        public virtual SubCategory SubCategory { get; set; }
    }

Step 2:

Generate views by using Entity Framework and by generating controller for category, subcategory and product.

Step 3:

Here is how productcontroller looks like.

  public class ProductController : Controller
    {
        private TestDataContext db = new TestDataContext();

        //
        // GET: /Product/

        public ActionResult Index()
        {
            //var products = db.Products.Include(p => p.Category).Include(p => p.SubCategory);
            return View(db.Products.ToList());
            //return View();
        }

        //
        // GET: /Product/Details/5

        public ActionResult Details(int id = 0)
        {
            Product product = db.Products.Find(id);
            if (product == null)
            {
                return HttpNotFound();
            }
            return View(product);
        }

        //
        // GET: /Product/Create

        public ActionResult Create()
        {
            var catid=1;
            try
            {
                 catid= (from c in db.Categories select c).FirstOrDefault().CategoryId;
            }
            catch (Exception ex)
            {
                catid=1;
            }
            ViewBag.CategoryId = new SelectList(db.Categories, "CategoryId", "CategoryName",catid);
            var subcategories = (from sub in db.SubCategories where sub.CategoryId == catid select new { sub.SubCategoryId, sub.SubCategoryName }).ToList();
            ViewBag.SubCategoryId = new SelectList(subcategories, "SubCategoryId", "SubCategoryName");
            //ViewBag.SubCategoryId = new SelectList(db.SubCategories, "SubCategoryId", "SubCategoryName");
            return View();
        }

        //
        // POST: /Product/Create

        [HttpPost]
        public ActionResult Create(Product product)
        {
            var subcatcheck = (from sub in db.SubCategories where sub.CategoryId == product.CategoryId && sub.SubCategoryId==product.SubCategoryId select new { sub.SubCategoryId, sub.SubCategoryName }).ToList();
            if (ModelState.IsValid && product.ProductName!=null && product.CategoryId!=null && product.SubCategoryId!=null && product.CategoryId!=0 && product.SubCategoryId!=0 && subcatcheck.Count!=0)
            {
                db.Products.Add(product);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.CategoryId = new SelectList(db.Categories, "CategoryId", "CategoryName", product.CategoryId);
            //ViewBag.SubCategoryId = new SelectList(db.SubCategories, "SubCategoryId", "SubCategoryName", product.SubCategoryId);
            var subcategories = (from sub in db.SubCategories where sub.CategoryId == product.CategoryId select new { sub.SubCategoryId, sub.SubCategoryName }).ToList();
            ViewBag.SubCategoryId = new SelectList(subcategories, "SubCategoryId", "SubCategoryName", product.SubCategoryId);
            return View(product);
        }

        //
        // GET: /Product/Edit/5

        public ActionResult Edit(int id = 0)
        {
            Product product = db.Products.Find(id);
            if (product == null)
            {
                return HttpNotFound();
            }
            ViewBag.CategoryId = new SelectList(db.Categories, "CategoryId", "CategoryName", product.CategoryId);
            ViewBag.SubCategoryId = new SelectList(db.SubCategories, "SubCategoryId", "SubCategoryName", product.SubCategoryId);
            return View(product);
        }

        //
        // POST: /Product/Edit/5

        [HttpPost]
        public ActionResult Edit(Product product)
        {
            if (ModelState.IsValid)
            {
                db.Entry(product).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.CategoryId = new SelectList(db.Categories, "CategoryId", "CategoryName", product.CategoryId);
            ViewBag.SubCategoryId = new SelectList(db.SubCategories, "SubCategoryId", "SubCategoryName", product.SubCategoryId);
            return View(product);
        }

        //
        // GET: /Product/Delete/5

        public ActionResult Delete(int id = 0)
        {
            Product product = db.Products.Find(id);
            if (product == null)
            {
                return HttpNotFound();
            }
            return View(product);
        }

        //
        // POST: /Product/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            Product product = db.Products.Find(id);
            db.Products.Remove(product);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
Step 4:

Edit the Create.cshtml under product folder in Views folder.

Here is what my create.cshtml looks like
@model TestData.Models.Product

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Product</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.CategoryId, "Category")
        </div>
        <div class="editor-field">
           @* @Html.DropDownList("CategoryId", String.Empty)*@
            @Html.DropDownList("CategoryId", null, new {onchange="this.form.submit(0);" })
            @Html.ValidationMessageFor(model => model.CategoryId)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.SubCategoryId, "SubCategory")
        </div>
        <div class="editor-field">
            @*@Html.DropDownList("SubCategoryId", String.Empty)*@
            @Html.DropDownList("SubCategoryId", null, new {onchange="this.form.submit(0);" })
            @Html.ValidationMessageFor(model => model.SubCategoryId)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.ProductName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.ProductName)
            @Html.ValidationMessageFor(model => model.ProductName)
        </div>

       

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

No comments:

Post a Comment

Comments are welcome, Please join me on my Linked In account

http://in.linkedin.com/pub/ritesh-tandon/21/644/33b

How to implement Captcha v3 in ASP.NET

 I was facing an issue of dom parsing in my website. I finally resolved it by using Google Captcha V3. Step 1: Get your keys from https:...