1

Creating a partialview for enter some personal details.I have to include 2 dropdownlist, 1 for country and other for states.When i select country as US then its want to populate all statenames from DB.If we select other country i want to replace dropdown for states to a textbox.How can i make it possible?

Thanks.

Charles Sprayberry
  • 7,741
  • 3
  • 41
  • 50
Sinoy Devassy
  • 564
  • 4
  • 11
  • 27
  • possible duplicate of [Cascading drop-downs in MVC 3 Razor view](http://stackoverflow.com/questions/4458970/cascading-drop-downs-in-mvc-3-razor-view) – Darin Dimitrov Feb 21 '12 at 10:51

1 Answers1

2

My suggestion is to use jquery ajax request to populate the drop down list options depending on country value. The ajax request could point to another PartialView that will return dropdown or textbox depending on parameter...

Let me know if you'll have any troubles with implementation, I'll enjoy helping you...


Action in controller:

public ActionResult StateNames(string country)
{
    if(country == "US")
    {
        var model = GetArrayOfUsStates();
        return View(model);
    }
    else
    {
        var model = string[0];
        return View(model);
    }
}

Partial View for your dropdown list:

@model string[]

@if(Model.Length == 0)
{
    <input type="text" name="state" />
}
else
{
    <select name="state">
        @foreach(var state in Model)
        {
            <option value="@state">@state</option>
        }
    </select>
}

Your page structure:

<select id="countryDDL">
   ...
</select>
<div id="stateDDLHolder">
</div>

Your jQuery code to get drop down:

$.ajax({ 
         url: '/YourController/StateNames/' + $('#countryDDL').val(),
         success: function(data) { $('#stateDDLHolder').html(data); }
});
Łukasz W.
  • 9,538
  • 5
  • 38
  • 63
  • How can i make this using jquery? – Sinoy Devassy Feb 22 '12 at 13:00
  • I've added example for you... please let me know if something in it will not work... I was writing it directly in the answer window and do not tested it, so there can be some misspellings etc. Anyway, hope that it will help.. – Łukasz W. Feb 23 '12 at 07:51
  • currently i loaded all states to my dropdownlist.Is it possible to replace the state dropdownlist to text box using jquery? – Sinoy Devassy Feb 23 '12 at 10:01
  • I used one textbox and one dropdownlist for this.By jquery i used show and hide options to work this.But I have to maintain the location if it is ddl or textbox. – Sinoy Devassy Feb 23 '12 at 10:07