I want to bind two dropdownlist. How can I call ddlObject.value from JavaScript to x.stateID at place with ******? Please help me.
Sorry my English :)
<div class="form-group">
<label>State</label>
@Html.DropDownList("StateID", (SelectList)ViewBag.Iller, "İl Seçiniz", new { @class = "form-control", @onChange = "chooseCity(this)" })
</div>
<div class="form-group">
<label>City</label>
<select id="City"></select>
</div>
<script>
function citySecim(ddlObject) {
document.getElementById("State").innerHTML = '@{
Context db = new Context();
List<City> cities = db.City.Where(x => x.stateID == ****I WANT TO WRITE ddlObject.value HERE****).ToList();
foreach (var city in cities)
{<option value="@city.cityID">@city.cityName</option>}
}';
}
</script>
You should not mix server-side and client-side code in view page, because server-side code immediately renders when the page is loading and you need another way to pass client-side variable value into server-based LINQ query.
Since you want to perform cascading dropdownlist, use change
event on first dropdown to trigger AJAX callback targeting a controller action instead, as given in example below:
HTML
<div class="form-group">
<label>State</label>
@Html.DropDownList("StateID", (SelectList)ViewBag.Iller, "İl Seçiniz", new { @class = "form-control", id = "state" })
</div>
<div class="form-group">
<label>City</label>
<select id="City"></select>
</div>
JS (jQuery)
$(function() {
$('#state').on('change', function () {
var stateId = $(this).val();
// use jQuery.ajax() or simplified jQuery.getJSON() to pass first dropdown value into action method
$.getJSON('@Url.Action("GetCity", "ControllerName")', { stateID: stateId }, function(result) {
if (!result)
return;
$('#City').append($('<option></option>').text('Select City').val(''));
$.each(result, function(index, item) {
$('#City').append($('<option></option>').text(item.cityName).val(item.cityID));
});
});
});
});
Controller Example
[HttpGet]
public ActionResult GetCity(int stateID)
{
using (Context db = new Context())
{
List<City> cities = db.City.Where(x => x.stateID == stateID).ToList();
// returns JSON data object from list of cities
return Json(cities, JsonRequestBehavior.AllowGet);
}
}
A similar DropDownList
approach can be found in Stephen's example here .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.