Posts tagged: jsonResult

Oct 30 2009

Multiple Dropdownlist in Asp.net MVC

Create Database Purchase then create two tables in Purchase Database

Category table and Subcategory table

Goto Category and SubCategory tables

Steps to Create Multiple DropDownlist controls in Asp.net MVC

Start -> Programs -> choose VS2008 or 2005 -> File-> Project -> choose web (project type Visual C#) ->choose Asp.Net MVC Web Application -> Application name is myFirstMVCapp -> Go to Solution explorer -> you will observe Model, View and Controller folder.

First Create Linq to Sql classes

In Model , create interface name is Categories.cs

using myFirstMVCapp.Models;

namespace myFirstMVCapp.Models

{

public interface ICategories

{

IQueryable<tblCategory> GetCategories();

IQueryable<tblSubCategory> GetSubCategories();

IQueryable<tblSubCategory> GetSubCategoriesByID(int catid);

}

public class Categories:ICategories

{

PurchaseDataContext db = new PurchaseDataContext();

public IQueryable<tblCategory> GetCategories()

{

return db.tblCategories;

}

public IQueryable<tblSubCategory> GetSubCategories()

{

return db.tblSubCategories;

}

public IQueryable<tblSubCategory> GetSubCategoriesByID(int catid)

{

return from subcategory in GetSubCategories()

where subcategory.CategoryID == catid

select subcategory;

}

}

}

In Controller, Create CategoriesController

using myFirstMVCapp.Models;

namespace myFirstMVCapp.Controllers

{

public class CategoriesController : Controller

{

//

// GET: /Categories/

PurchaseDataContext db = new PurchaseDataContext();

#region “Repository”

ICategories categoriesRepository;

ISubCategories subCategoriesRepository;

public CategoriesController() :

this(new Categories())

{

}

public CategoriesController(ICategories repository)

{

categoriesRepository = repository;

}

#endregion

public ActionResult Index()

{

ViewData["Categories"] = new SelectList

(

db.tblCategories,

CategoryID“,

CategoryName

);

return View();

}

#region “JSonResult”

public JsonResult FindSubCategoriesByCatID(int catID)

{

// Simulate Loading Data “wait”

System.Threading.Thread.Sleep(500);

// return Json result using LINQ to SQL

return new JsonResult

{

Data = categoriesRepository.GetSubCategoriesByID(catID)

};

}

#endregion

}

}

In Site.Master add below lines inside head tags

<head>

<script src=”../../Scripts/jquery-1.3.2.min.js” type=”text/javascript”></script>

<asp:ContentPlaceHolder ID=”HeadContent” runat=”server” />

</head>

Design page coding in Categories folder index page

<%@ Page Title=”" Language=”C#” MasterPageFile=”~/Views/Shared/Site.Master” Inherits=”System.Web.Mvc.ViewPage<myFirstMVCapp.Models.PurchaseDataContext>” %>

<asp:Content ID=”Content1″ ContentPlaceHolderID=”TitleContent” runat=”server”>

Index

</asp:Content>

<asp:Content ID=”Head” ContentPlaceHolderID=”HeadContent” runat=”server”>

<script type=”text/javascript”>

$(document).ready(function() {

$(”select#Categories“).change(function() {

var color = $(”#Categories > option:selected“).attr(”value”);

$.ajax({

type: “GET”,

contentType: “application/json; charset=utf-8″,

url: “FindSubCategory/” + color,

data: “{}”,

dataType: “json”,

success: function(data) {

$(’#SubCategoryDiv > div’).remove(); // remove any existing SubCategory

if (data.length > 0) {

var options = ”;

for (p in data) {

var product = data[p];

options += “<option value=’” + product.SubCategoryID + “‘>” + product.SubCategory + “</option>”;

}

$(”#SubCategory“).removeAttr(’disabled’).html(options);

} else {

$(”#SubCategory“).attr(’disabled’, true).html(”);

$(”#SubCategoryDiv”).append(’<div>(None Found)</div>’);

}

}

});

});

});

</script>

</asp:Content>

<asp:Content ID=”Content2″ ContentPlaceHolderID=”MainContent” runat=”server”>

<h2>Index</h2>

<p>

<label for=”Categories“>Categories:</label>

<%=Html.DropDownList(”Categories“)%>

</p>

<p>

<div id=”SubCategoryDiv”></div>

</p>

<p>

<label for=”SubCategory”>SubCategory:</label>

<select id=”SubCategory” disabled></select>

</p>

</asp:Content>

In Global.asax file

routes.MapRoute(

FindSubCategory“,

FindSubCategory/{catID}”,

new { controller = “Categories”, action = “FindSubCategoriesByCatID“, catID = “” }

);

FindSubCategory is from JSon Script

Url: FindSubCategory

In Global.asax: FindSubCategory

FindSubCategoriesByCatID is from CategoriesController Json Function

#region “JSonResult”

public JsonResult FindSubCategoriesByCatID(int catID)

{

// Simulate Loading Data “wait”

System.Threading.Thread.Sleep(500);

// return Json result using LINQ to SQL

return new JsonResult

{

Data = categoriesRepository.GetSubCategoriesByID(catID)

};

}

#endregion

Alibi3col theme by Themocracy