How to set state of dropdownlist for default value to the one stored in database in edit view when using auto generated models via edmx (not created manually).
Here is my code :
View :
#Html.DropDownListFor(model => model.site_id, new SelectList(ViewBag.site_id, "id", "name"), "Select Any", new {#class="form-control",required="required",autofocus="autofocus" })
Controller :
ViewBag.site_id = dbContext.axi_sites;
Been looking for the solution for quite a while, none match to the exact requirement.
Why should we bother. We can use jquery too.
add jquery 1.10.3 in your code.
and code below in your page where you want dropdownlistfor selected value
write in View part
<script type="text/JavaScript">
$(document).ready(function () {
$('#site').val(#Model.site_id);
});
</script>
#Html.DropDownListFor(model => model.site_id, new SelectList(ViewBag.site_id, "id", "name"), "Select Any", new {#class="form-control",required="required",autofocus="autofocus",id="site" })
C# code:
public class MyClass {
public int Id { get; set; }
public string Name { get; set; }
}
var list = new[] {
new MyClass { Id = 1, Name = "Name1" },
new MyClass { Id = 2, Name = "Name2" },
new MyClass { Id = 3, Name = "Name3" }
};
var selectList = new SelectList(list, "Id", "Name", 2);
ViewBag.DDL = selectList;
In View:
#Html.DropDownListFor(model => model.site_id,
ViewBag.DDL as SelectList,
"Select Any",
new {#class="form-control",required="required",autofocus="autofocus" })
Html Output:
<select id="site_id" name="site_id" required="required" class="form-control">
<option value="1">Name1</option>
<option selected="selected" value="2">Name2</option>
<option value="3">Name3</option>
</select>
Related
I have the following dropdownlist in my view:
#{
var listado = new List<SelectListItem>()
{
new SelectListItem()
{
Text ="YES",
Value ="1"
},
new SelectListItem()
{
Text = "NO",
Value = "2"
}
};
}
<div class="form-group">
<label class="control-label">Is it True ?</label>
#Html.DropDownList("miDropDownList",listado)
</div>
I want to get the selected value 'YES' or 'NO' to do something in the controller like so:
IActionResult ControllerAction(){
var theValue = dropdownList.SelectedValue //this is pseudocode syntax but you understand I want to get
//the value
// with the value I will do something like this:
User userinstance = new User {
Id = 1,
Name = "john",
isJohnTall = theValue.Value
}
}
I want something simple in other answers I've seen DropDownLists that are bound to models, but I just want to get strings selected in the dropdown and be able to do something with them in the controller.
You can use JQuery with ajax.
Something like this:
<div class="form-group">
<label class="control-label">Is it True ?</label>
#Html.DropDownList("miDropDownList", listado, new { #onchange = "GetYesOrNo()"})
</div>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script>
function GetYesOrNo() {
var selectElement = document.querySelector('#miDropDownList');
var option = selectElement.value;
$.ajax({
url: '/Home/GetYesOrNo',
type: 'GET',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
mimeType: 'text/html',
data: { getOption : option },
success: function (returnValue) {
alert(returnValue);
}
});
};
</script>
And in Home Controller, add this JsonResult:
public JsonResult GetYesOrNo(int getOption)
{
if (getOption == 1) return Json("Option: YES");
return Json("Option: NO");
}
You can use a form to submit your data.
The form will submit Value, so you can modify your value as Text.
You can change your code like below.
View:
#{
var listado = new List<SelectListItem>()
{
new SelectListItem()
{
Text ="YES",
Value ="YES"
},
new SelectListItem()
{
Text = "NO",
Value = "NO"
}
};
}
#using (Html.BeginForm("GetYesOrNo", "User"))
{
<div class="form-group">
<label class="control-label">Is it True ?</label>
#Html.DropDownList("miDropDownList", listado)
</div>
<button type="submit">Find</button>
}
Action:
public IActionResult GetYesOrNo(string miDropDownList)
{
//.....
return View();
}
Test result:
And how to bind to the model with dropdownlist,you can see my this reply,it may helpful.
First of all I must say this I am new to MVC4 and developing this app and learning MVC4 simultaneously :).
In this app,
Below is the parent view where 3 partial views are rendered also there is one button:
[code]
<td id="track">#Html.Partial("_Track",Model)</td><br>
<td id="tech">
<div id="Technologies"> #Html.Partial("_Technology",Model)
</div></td></tr>
..
[some code]
..
<td class="subtopic">
<div class="subtopiclist" id="subque">#Html.Partial("_Subtopics",Model)</div><br>
<input type="Submit" value="Fetch Interview Questions" name="Fetch" id="Fetch" />
</td>
Partial View1 (it contains dropdownlist) :
#model MvcApplication3.Models.CommonWrapper
#using (Ajax.BeginForm("SelectTrack", "Home", new AjaxOptions { UpdateTargetId = "Technologies" }))
{
#Html.DropDownListFor(
m=>m.SelectedTrackId,
new SelectList(Model.track, "TrackId", "TrackName"),
string.Empty
)
}
<script type="text/javascript">
$('#SelectedTrackId').change(function () {
$(this).parents('form').submit();
});
</script>
Parital View2 (it contains dropdownlist):
#model MvcApplication3.Models.CommonWrapper
#if (Model.tech != null && Model.tech.Count() > 0)
{
using (Ajax.BeginForm("SelectTechnology", "Home", new AjaxOptions { UpdateTargetId = "subque" }))
{
#Html.HiddenFor(m => m.SelectedTrackId)
#Html.DropDownListFor(
m => m.SelectedTechId,
new SelectList(Model.tech, "TechId", "TechName"),
string.Empty
)
}
}
<script type="text/javascript">
$(document).on('change', '#SelectedTechId', function () {
$(this).parents('form').submit();
});
</script>
Partial view 3 (it contains multiple checkboxes):
#if (Model.subtopic != null && Model.subtopic.Count() > 0)
{
<table>
#for (int i = 0; i < Model.subtopic.Count; i++)
{
<tr><td>
#Html.CheckBoxFor(m => m.subtopic[i].IsSelected, new { id = "subTopic_" + i })
#Html.HiddenFor(m => m.subtopic[i].SubtopicName)
#Html.DisplayFor(m => m.subtopic[i].SubtopicName)
<td>
</tr>
}
</table>
}
Now In parent view, I want to fetch the values from these three partial views.Also, I need to send these fetched values to controller.
How to do this ? can anybody please help me on this.
Thanks in advance
Added controller code :
[HttpPost]
public ActionResult SelectTrack(int? selectedTrackId)
{
CommonWrapper wrapper = new CommonWrapper();
wrapper.tech = new List<TechModel>();
if (selectedTrackId.HasValue)
{
wrapper.tech = (from s in CommonWrapper.GetTechnology()
where s.TrackId == selectedTrackId
orderby s.TechName
select s).ToList();
}
return PartialView("_Technology", wrapper);
}
[HttpPost]
public ActionResult SelectTechnology(int? selectedTechId)
{
CommonWrapper wrapper = new CommonWrapper();
wrapper.subtopic = new List<SubtopicsModel>();
if (selectedTechId.HasValue)
{
wrapper.subtopic = (from s in CommonWrapper.GetSubtopics()
where s.TechId == selectedTechId
orderby s.SubtopicName
select s).ToList();
}
return PartialView("_Subtopics", wrapper);
}
Try changing the ajax forms to simply using jquery to post to a desired controller action. This then separates your partial views from requiring an update target.
You can apply this method for each of your drop down lists calling a different controller action.
Remove your Ajax.BeginForm's and the corresponding jquery code and replace each with the below.
Parent View
<script type="text/javascript">
$(function ()
{
$("#SelectedTrackId").change(function ()
{
var selectedValue = $(this).val();
$.ajax(
{
type: "post",
data: selectedValue,
url: url,
success: function (data)
{
// data contains your partial view
$("#some-container-id").html(data);
}
});
});
});
</script>
I'd put together a ViewModel and put this in the [HttpPost] Controller Action
Hope this helps
Christian
I have four controls on the page, a simple form with first and last names, date of birth and this drop down that contains some names of countries. When I make changes to the these controls I am able to see those changes in my viewModel that is passed in as a parameter in the SavePersonDetails POST below, but I never see the LocationId updated in that view model and I am not sure why.
This is what I have in my markup, Index.cshtml:
#model Mvc4withKnockoutJsWalkThrough.ViewModel.PersonViewModel
#using System.Globalization
#using Mvc4withKnockoutJsWalkThrough.Helper
#section styles{
#Styles.Render("~/Content/themes/base/css")
<link href="~/Content/Person.css" rel="stylesheet" />
}
#section scripts{
#Scripts.Render("~/bundles/jqueryui")
<script src="~/Scripts/knockout-2.1.0.js"></script>
<script src="~/Scripts/knockout.mapping-latest.js"></script>
<script src="~/Scripts/Application/Person.js"></script>
<script type="text/javascript">
Person.SaveUrl = '#Url.Action("SavePersonDetails", "Person")';
Person.ViewModel = ko.mapping.fromJS(#Html.Raw(Json.Encode(Model)));
var userObject = '#Html.Raw(Json.Encode(Model))';
var locationsArray = '#Html.Raw(Json.Encode(Model.Locations))';
var vm = {
user : ko.observable(userObject),
availableLocations: ko.observableArray(locationsArray)
};
ko.applyBindings(vm);
</script>
}
<form>
<p data-bind="with: user">
Your country:
<select data-bind="options: $root.availableLocations, optionsText: 'Text', optionsValue: 'Value', value: LocationID, optionsCaption: 'Choose...'">
</select>
</p>
</form>
This is my View Model:
public class PersonViewModel
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
public string LocationId { get; set; }
public IEnumerable<SelectListItem> Locations { get; set; }
}
I have a simple controller that loads my Person and a drop down list containing three countries.
private PersonViewModel _viewModel;
public ActionResult Index()
{
var locations = new[]
{
new SelectListItem { Value = "US", Text = "United States" },
new SelectListItem { Value = "CA", Text = "Canada" },
new SelectListItem { Value = "MX", Text = "Mexico" },
};
_viewModel = new PersonViewModel
{
Id = 1,
FirstName = "Test",
LastName = "Person",
DateOfBirth = new DateTime(2000, 11, 12),
LocationId = "", // I want this value to get SET when the user changes their selection in the page
Locations = locations
};
_viewModel.Locations = locations;
return View(_viewModel);
}
[HttpPost]
public JsonResult SavePersonDetails(PersonViewModel viewModel)
{
int id = -1;
SqlConnection myConnection = new SqlConnection("server=myMachine;Trusted_Connection=yes;database=test;connection timeout=30");
try
{
// omitted
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
finally
{
myConnection.Close();
}
return Json(id, "json");
}
Lastly, here is my Person.js file, I am using knockout
var Person = {
PrepareKo: function () {
ko.bindingHandlers.date = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
element.onchange = function () {
var observable = valueAccessor();
observable(new Date(element.value));
}
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var observable = valueAccessor();
var valueUnwrapped = ko.utils.unwrapObservable(observable);
if ((typeof valueUnwrapped == 'string' || valueUnwrapped instanceof String) && valueUnwrapped.indexOf('/Date') === 0) {
var parsedDate = Person.ParseJsonDate(valueUnwrapped);
element.value = parsedDate.getMonth() + 1 + "/" + parsedDate.getDate() + "/" + parsedDate.getFullYear();
observable(parsedDate);
}
}
};
},
ParseJsonDate: function (jsonDate) {
return new Date(parseInt(jsonDate.substr(6)));
},
BindUIwithViewModel: function (viewModel) {
ko.applyBindings(viewModel);
},
EvaluateJqueryUI: function () {
$('.dateInput').datepicker();
},
RegisterUIEventHandlers: function () {
$('#Save').click(function (e) {
// Check whether the form is valid. Note: Remove this check, if you are not using HTML5
if (document.forms[0].checkValidity()) {
e.preventDefault();
$.ajax({
type: "POST",
url: Person.SaveUrl,
data: ko.toJSON(Person.ViewModel),
contentType: 'application/json',
async: true,
beforeSend: function () {
// Display loading image
},
success: function (result) {
// Handle the response here.
if (result > 0) {
alert("Saved");
} else {
alert("There was an issue");
}
},
complete: function () {
// Hide loading image.
},
error: function (jqXHR, textStatus, errorThrown) {
// Handle error.
}
});
}
});
},
};
$(document).ready(function () {
Person.PrepareKo();
Person.BindUIwithViewModel(Person.ViewModel);
Person.EvaluateJqueryUI();
Person.RegisterUIEventHandlers();
});
As you can see, I have the data in the page but none of them show as selected
Your solution is overly complex and is leading to certain weirdness with your data. Instead of trying to patch the Titanic, your best bet is to start over and simplify:
Your page's model contains all the information you need. There's no need to try to create two totally separate view models to work with the user data versus locations. With the mapping plugin, you can specify different "view models" for various objects in your main view model, and there's a simpler pattern that can be followed to set all that up. Here's what I would do:
// The following goes in external JS file
var PersonEditor = function () {
var _init = function (person) {
var viewModel = PersonEditor.PersonViewModel(person);
ko.applyBindings(viewModel);
_wireEvents(viewModel);
}
var _wireEvents = function (viewModel) {
// event handlers here
}
return {
Init: _init
}
}();
PersonEditor.PersonViewModel = function (person) {
var mapping = {
'Locations': {
create: function (options) {
return new PersonEditor.LocationViewModel(options.data)
}
}
}
var model = ko.mapping.fromJS(person, mapping);
// additional person logic and observables
return model;
}
PersonEditor.LocationViewModel = function (location) {
var model = ko.mapping.fromJS(location);
// additional location logic and observables
return model;
}
// the following is all you put on the page
<script src="/path/to/person-editor.js"></script>
<script>
$(document).ready(function () {
var person = #Html.Raw(#Json.Encode(Model))
PersonEditor.Init(person);
});
</script>
Then all you need to bind the select list to the locations array is:
<p>
Your country:
<select data-bind="options: Locations, optionsText: 'Text', optionsValue: 'Value', value: LocationId, optionsCaption: 'Choose...'">
</select>
</p>
Based on your updated question, do this.
1.We do not need locationsArray actually. Its already in user.Locations (silly me)
2.On Index.cshtml, page change the JavaScript like this.
var userObject = #Html.Raw(Json.Encode(Model)); // no need for the quotes here
jQuery(document).ready(function ($) {
Person.PrepareKo();
Person.EvaluateJqueryUI();
Person.RegisterUIEventHandlers();
Person.SaveUrl = "#Url.Action("SavePersonDetails", "Knockout")";
Person.ViewModel = {
user : ko.observable(userObject)
};
Person.BindUIwithViewModel(Person.ViewModel);
});
3.On your Person.js page, inside RegisterUIEventHandlers #Save button click event, do this.
$('#Save').click(function (e) {
var updatedUser = Person.ViewModel.user();
updatedUser.Locations.length = 0; // not mandatory, but we don't need to send extra payload back to server.
// Check whether the form is valid. Note: Remove this check, if you are not using HTML5
if (document.forms[0].checkValidity()) {
e.preventDefault();
$.ajax({
type: "POST",
url: Person.SaveUrl,
data: ko.toJSON(updatedUser), // Data Transfer Object
contentType: 'application/json',
beforeSend: function () {
// Display loading image
}
}).done(function(result) {
// Handle the response here.
if (result > 0) {
alert("Saved");
} else {
alert("There was an issue");
}
}).fail(function(jqXHR, textStatus, errorThrown) {
// Handle error.
}).always(function() {
// Hide loading image.
});
}
});
5.Finally, our markup
<p data-bind="with: user">
Your country:
<select data-bind="options: Locations,
optionsText: 'Text',
optionsValue: 'Value',
value: LocationId,
optionsCaption: 'Choose...'">
</select>
</p>
On an unrelated side-note,
The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are
deprecated as of jQuery 1.8. To prepare your code for their eventual
removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.
So i'm building a simple mvc4 application, I have created all base models for the creation of the DB, from these classes I could naturally create basic controllers with their matching views.
Now my problem: I have the basic create actionresult + view and in this view I wanted that the user would be able to select some values from a dropdownlist which would make creation of new objects simpler.
I tried to achieve this with a second form in my view (the first one is the basic create form) now if I want to use these dropdowns (they filter each other(so first the user must specify a continent, then the dropdown of the countries only shows countries from that continent and after he specifies a country the region dropdown gets updated :) )) the submit of the basic view is always automatically called.
so making the dropdowns update themselves isn't the problem :s it's that the form for the create automatically validates when the dropdowns are updated
this is the controller where the dropdowns filter each other
//
// GET: /FederationCenter/Create
public ActionResult Create(string searchRegion, string searchCountry, string searchContinent)
{
var countries = from c in db.Countries select c;
if (!String.IsNullOrEmpty(searchContinent))
{
Continent searchContinentEnumValue = (Continent)Enum.Parse(typeof(Continent), searchContinent);
countries = from c in db.Countries where ((int)c.Continent).Equals((int)searchContinentEnumValue) select c;
}
var regions = from r in db.Regions where r.Country.Name.Equals(searchCountry) select r;
ViewBag.searchContinent = new SelectList(Enum.GetNames(typeof(SchoolCup.Domain.Continent)));
ViewBag.searchCountry = new SelectList(countries, "Name", "Name");
ViewBag.searchRegion = new SelectList(regions, "Name", "Name");
return View();
}
//
// POST: /FederationCenter/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(NSSF nssf, string searchRegion, string searchCountry, string searchContinent)
{
var countries = from c in db.Countries select c;
if (!String.IsNullOrEmpty(searchContinent))
{
Continent searchContinentEnumValue = (Continent)Enum.Parse(typeof(Continent), searchContinent);
countries = from c in db.Countries where ((int)c.Continent).Equals((int)searchContinentEnumValue) select c;
}
var regions = from r in db.Regions where r.Country.Name.Equals(searchCountry) select r;
ViewBag.searchContinent = new SelectList(Enum.GetNames(typeof(SchoolCup.Domain.Continent)));
ViewBag.searchCountry = new SelectList(countries, "Name", "Name");
ViewBag.searchRegion = new SelectList(regions, "Name", "Name");
if (ModelState.IsValid)
{
var naam = Request["searchRegion"];
Region creatie = (from c in db.Regions where c.Name.Equals(naam) select c).SingleOrDefault();
nssf.ISFId = 1;
nssf.RegionId = creatie.RegionId;
db.NSSFs.Add(nssf);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(nssf);
}
and this is my view
#model SchoolCup.Domain.POCO.NSSF
#{
ViewBag.Title = "Create";
}
<h2>Create NSSF</h2>
<div>
#using (Html.BeginForm(null, null, FormMethod.Post, new { name = "form" }))
{
#Html.AntiForgeryToken()
#Html.DropDownList("searchContinent", null, "-- All continents --", new { onchange = "sendForm()" })
#Html.DropDownList("searchCountry", null, "-- All countries --", new { onchange = "sendForm()" })
#Html.DropDownList("searchRegion", null, "-- All regions --", new { onchange = "sendForm()" })
<>
<input type="submit" name= value="Search" />
}
</div>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>NSSF</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
some more inputs
</fieldset>
<p>
<input type="submit" value="Create" />
#Html.ActionLink("Back to List", "Index", null, new { #class = "button" })
</p>
}
#section Scripts {
<script type="text/javascript">
function sendForm() {
document.form.submit()
}
</script>
}
I've been looking for at least a day and I don't know how to solve this
with regards
Alexander
How about either (1) using JQuery and loading the drop-down with a Partial view returned by your controller or (2) you could have an AJAX call that would return your values as a JSON object mapped from your entity and you can render them in the drop-down. This way your form won't be submitted every time you update a drop-down.
The first solution might look something like this:
JQUERY
<script>
$("#searchContinent").change(function() {
$("#searchCountry").load("/YourController/GetCountries", { 'continentId': $(this).val() },
function (response, status, xhr) {
if (status == "error") {
alert("An error occurred while loading the results.");
}
});
});
</script>
#Html.DropDownList("searchContinent", null, "-- All continents --" })
<div id="searchCountry">
<!--the newly created drop-down will be placed here-->
</div>
(EDIT)
For Javascript you might try something like this:
YOUR CURRENT VIEW
#Html.DropDownList("searchContinent", null, "-- All continents --", new { onchange = "getCountries(this)" })
<div id="searchCountry">
<!--the newly created drop-down will be placed here-->
</div>
<script>
function getCountries(input){
var selectedValue = input.options[input.selectedIndex].value;
var xhReq = new XMLHttpRequest();
xhReq.open("GET", "YourController/GetCountries?continentId="+selectedValue, false);
xhReq.send(null);
var serverResponse = xhReq.responseText;
document.getElementById("searchCountry").innerHTML=serverResponse ;
}
</script>
DISCLAIMER: This I have never tried so if it's wrong don't hesitate to let me know and correct it if necessary
(END EDIT)
CONTROLLER
public ActionResult GetCountries(string continentId)
{
/*Get your countries with your continentId and return a Partial View with a list of
countries as your model*/
return PartialView(countryList);
}
GetCountries VIEW
#model IEnumerable<SchoolCup.Domain.Country>
#Html.DropDownListFor( 0, Model)
I used the below method for doing Async postback using AJAX. This works fine on clicking submit. But i would like to know, is that possible to call various ActionMethods in a controller via AJAX.
I would like to implement something like cascading dropdown. How to call different ActionMethod via AJAX on dropdown value change?
Here is the code which call only one ActionMethod on submitting form.
View
#{
ViewBag.Title = "Index";
var options = new AjaxOptions()
{
Url = Url.Action("Index", "City"),
LoadingElementId = "saving",
LoadingElementDuration = 2000,
Confirm = "Are you sure you want to submit?"
};
}
<h2>Index</h2>
#using (Ajax.BeginForm(options))
{
<div id="saving">Loading...</div>
#Html.DropDownList("Countries",ViewBag.Countries as SelectList)<input type="submit" />
}
Controller
public ActionResult Index()
{
IEnumerable<SelectListItem> selectListItems = new []
{
new SelectListItem{ Text = "US",Value = "1" }
};
ViewBag.Countries = selectListItems;
return View();
}
public ActionResult GetState(string countryId)
{
IEnumerable<SelectListItem> selectListItems = new[]
{
new SelectListItem { Text = "Tennesse", Value = "1" },
new SelectListItem { Text = "Newyork", Value = "2" }
};
return View();
}
The answer to your first question "is that possible to call various ActionMethods in a controller via AJAX" is a big yes. You may call any action method from your controller through Ajax though the only result generated depends on various things like whether you send a view or partial view or JSON result.
for your next question :
I will be posting some codes
Controller.cs
public JsonResult getCity(string country)
{
var temp = (from cntry in db.Table3.OrderBy(s => s.country)
where (string.Compare(cntry.country, country) == 0)
select cntry.city).ToList();
return Json(temp, JsonRequestBehavior.AllowGet);
}
View
<h1>
Countries</h1>
<select name="countries" class="combo">
<option value=""></option>
#{
foreach (var t in (List<string>)ViewBag.countries)
{
<option value=#t>#t</option>
}
}
</select>
<h1>
State</h1>
<select name="city" class="combo2">
</select>
<div id="tese">
</div>
#*
The following jquery code finds the selected option from country dropdown
and then sends an ajax call to the Home/getcity method
and finally populate it to the city dropdown
*#
<script type="text/javascript">
$('body').on('change', '.combo', function () {
var selectedValue = $(this).val();
alert(selectedValue);
$.get("/Home/getcity", { country: selectedValue }, function (data) {
$("#tese").html(data);
$(".combo2").html("<option value = \"\"></option>")
$.each(data, function (index, value) {
$(".combo2").append("<option value = \"" + value + "\">" + value + "</option>");
});
$(".combo2").html()
});
});
</script>
This will show a dropdown of countries list. Once a country is selected it will render a new dropdown of city list
public JsonResult getCity(string country)
{
var temp = (from cntry in db.Table3.OrderBy(s => s.country)
where (string.Compare(cntry.country, country) == 0)
select cntry.city).ToList();
return Json(temp, JsonRequestBehavior.AllowGet);
}
View
<h1>
Countries</h1>
<select name="countries" class="combo">
<option value=""></option>
#{
foreach (var t in (List<string>)ViewBag.countries)
{
<option value=#t>#t</option>
}
}
</select>
<h1>
State</h1>
<select name="city" class="combo2">
</select>
<div id="tese">
</div>
#*
The following jquery code finds the selected option from country dropdown
and then sends an ajax call to the Home/getcity method
and finally populate it to the city dropdown
*#
<script type="text/javascript">
$('body').on('change', '.combo', function () {
var selectedValue = $(this).val();
alert(selectedValue);
$.get("/Home/getcity", { country: selectedValue }, function (data) {
$("#tese").html(data);
$(".combo2").html("<option value = \"\"></option>")
$.each(data, function (index, value) {
$(".combo2").append("<option value = \"" + value + "\">" + value + "</option>");
});
$(".combo2").html()
});
});
</script>