I’m creating a search application in mvc3 where i have 2 tables :
1.State :Id(pk) and state_name
2.District:Id(pk),s_id(f.k.), District_name
I am using code first and EF and have database created for it called Search
I want my index to show all states in drop down list
following is my State.cs code
public partial class State
{
public State()
{
this.Districts = new HashSet<District>();
this.Search_master = new HashSet<Search_master>();
}
public int Id { get; set; }
public string State_name { get; set; }
public virtual ICollection<District> Districts { get; set; }}
this is my District class:
public partial class District
{
public District()
{
this.Search_master = new HashSet<Search_master>();
}
public int Id { get; set; }
public string District_name { get; set; }
public int StateId { get; set; }
public virtual State State { get; set; } }
I also created one viewmodel for state and district….
public class State_district
{
public string selectedstate { get; set; }
public IEnumerable<State> states { get; set; }
public string selecteddistrict { get; set; }
public IEnumerable<District> districts { get; set; }
}
inside controller i have written:
public ActionResult Index()
{
var model = new State_district { states = db.States, districts = db.Districts };
return View(model);}
in the view:
<div class="editor-field" id="districtID">*Select State:-
@Html.DropDownListFor(x => x.states, new SelectList(Model.states, "Id", "State_Name"))
</div>
With this i am able to see my 1st ddl but how can i bind it with my second list…..
I need code that help me to show me district from selected state only…..can anybody help me with the jQuery code…
thank you in advance!!
You are trying to implement a dynamic/cascading dropdown and there are a lot of resources on the internet which can help you with this:
A simple non-AJAX implementation would work like this:
You have your first dropdown, created normally:
Your second dropdown, or dependent dropdown, will need to store some information about which parent item each item is associated with. e.g.:
Notice how each entry in the dropdown has an additional attribute
data-state-id. We need this information in order to know which values to show given the current active State.And then you would add an event handler which handles the change event on your primary dropdown, and update the dependent dropdown accordingly:
Please note the code provided are to demonstrate the concept only.