I want add items on the dropdownlist on the change of another.
Suppose I have country list in one dropdownlist and as a user select country state of that country fill in another dropdownlist.
I tried it lot but i am unable to do in mvc...please solve my problem.....
Loading
Bhavik SolankiPosted Nov 7, 2011, 8:10 AM
For Fill Dropdown Dynamically you need to use $.getJSON method using this you can get data from your controller you have one controller city when one action is there
Code in MVc Site
public class CityController {
public ActionResult FillCity(int64 CountryId)
{
SelectList CityList= (SelectList )('Code for collect from database
return Json(agreementList);
)
}
Routes in global.asax
routes.MapRoute(
"GetCityList",
"City/{ CountryId } ",
new { controller = "City", action = " FillCity", CountryId = "0" });
Code in Javascript
$.getJSON("/City"+ CountryId, null, function(jsonSiteData) {
for (var i = 0; i < jsonSiteData.length; i++) {
//Here you need to fill data into option
}
}
Regards,
Bhavik
Rohit KesharwaniPosted Sep 8, 2011, 3:35 AM
Satyapriya NayakPosted Sep 7, 2011, 2:19 PM
Here is your solution,Run the attachment.
Default.aspx code
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
Default.aspx.cs code
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
string strConnString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
string str;
SqlCommand com;
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(strConnString);
if (!IsPostBack)
{
DropDownList_country.Items.Add("Choose country");
con.Open();
str = "select country from area group by country";
com = new SqlCommand(str, con);
SqlDataReader reader = com.ExecuteReader();
while (reader.Read())
{
DropDownList_country.Items.Add(reader["country"].ToString());
}
reader.Close();
con.Close();
}
DropDownList_state.Items.Clear();
}
protected void DropDownList_country_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(strConnString);
con.Open();
str = "select * from area where country='" + DropDownList_country.SelectedItem.Text + "'";
com = new SqlCommand(str, con);
SqlDataReader reader = com.ExecuteReader();
while (reader.Read())
{
DropDownList_state.Items.Add(reader["state"].ToString());
}
reader.Close();
con.Close();
}
}
Thanks
If this post helps you mark it as answer