Ajax not appending to my drop down list (C# MVC) - javascript

I'm busy with 2 drop downs. The first one is country and loads fine, then on country change I call ajax to populate the province drop down.
The code works fine and when I put an alert in my ajax call it shows the correct data being created but it doesn't append it the drop down so the values aren't available.
Drop Down
<div class="form-group">
<label class="col-md-3 col-xs-5 control-label">Country:</label>
<div class="col-md-9 col-xs-7">
#Html.DropDownListFor(x => x.CountryId, (IEnumerable<SelectListItem>)ViewBag.CountryItems, "Please Select", new { #id = "ddlCountry", #class = "form-control select" })
</div>
</div>
<div class="form-group">
<label class="col-md-3 col-xs-5 control-label">Province:</label>
<div class="col-md-9 col-xs-7">
#Html.DropDownListFor(x => x.ProvinceId, Enumerable.Empty<SelectListItem>(), "Please Select", new { #id = "ddlProvince", #class = "form-control select" })
</div>
</div>
The Ajax
<script>
$('#ddlCountry').change(function () {
var countries = document.getElementById("ddlCountry");
var countryId = countries.options[countries.selectedIndex].value;
$.ajax({
url: "/Master/GetProvinces",
data: { countryId: countryId },
dataType: "json",
type: "GET",
error: function () {
alert(" An error occurred.");
},
success: function (data) {
$.each(data, function (i) {
var optionhtml = '<option value="' + data[i].Value + '">' + data[i].Text + '</option>';
$("#ddlProvince").append(optionhtml);
});
}
});
});
</script>
The code behind
public ActionResult GetProvinces(string countryId)
{
IEnumerable<SelectListItem> ProvinceItems = null;
if (!string.IsNullOrEmpty(countryId))
{
ProvinceItems = BusinessAPI.ProvinceManager.GetAllProvincesByCountryId(Convert.ToInt32(countryId)).Select(ci => new SelectListItem
{
Value = ci.Id.ToString(),
Text = ci.Name
});
}
return Json(ProvinceItems, JsonRequestBehavior.AllowGet);
}

I found the problem.
I have a javascript file in there thats causing some issues.
<script type="text/javascript" src="../../Scripts/js/plugins/bootstrap/bootstrap-select.js"></script>
This came with the template I bought and it helps with the way the dropdowns and stuff works.
With that javascript file you have to add .selectpicker('refresh'); to the append to load it properly like this
$("#ddlProvince").append(optionshtml).selectpicker('refresh');
That might be slow when loading a large amount of data so just refreshing the dropdown once after everything done works well. Here is the code that works well for me now
$('#ddlCountry').change(function () {
var countries = document.getElementById("ddlCountry");
var countryId = countries.options[countries.selectedIndex].value;
$.ajax({
url: "/Master/GetProvinces",
data: { countryId: countryId },
dataType: "json",
async: true,
type: "GET",
error: function () {
alert(" An error occurred.");
},
success: function (data) {
("#ddlProvince").empty();
$.each(data, function (i) {
var optionshtml = '<option value="' + data[i].Value + '">' + data[i].Text + '</option>';
$("#ddlProvince").append(optionshtml);
});
$("#ddlProvince").selectpicker('refresh');
}
});
});

Related

Loading dropdown list after modal for m is updated

I very new to MVC and I have an issue that was real easy in webforms. I have a drop down list on a form. I have a button that loads a modal form that allows the user to add an item to the DB on the fly. I then need to update the dropdown list with the new contents of the table. I realize I need ajax to do this but I am very confused on how to initiate the update!
I have the form with the following dropdown.
<div class="form-group form-group-sm required">
#Html.LabelFor(m => m.ListingData.Transmission, new { #class = "col-md-4 control-label" })
<div class="col-md-8">
#Html.DropDownListFor(m => m.ListingData.Transmission, (SelectList)ViewBag.TransmissionList, new { #class = "form-control"} )
#Html.ValidationMessageFor(m => m.ListingData.Transmission, "", new { #class = "text-danger" })
<p class="form-text"><a data-modal='' href='#Url.Action("QATransmission", "Admin", new { ListingId = Model.ListingData.ListingId}))' id=''>Quick Add Manufacturer</a></p>
</div>
</div>
I use this ajax in the main page to call the load the list code in the controller.
$(function () {
$.ajax({
type: "GET",
url: "Admin/LoadTransmissionList",
data: JSON,
cache: false,
success: function (data) {
$.each(data, function (index, value) {
$('#Transmission').append('<option value="' + value.TransmissionText + '">' + value.TransmissionText + '</option>');
});
}
});
});
This is my controller code for the list:
[HttpPost]
public JsonResult LoadTransmissionList()
{
var lstTrans = db.Transmissions.ToList();
List<SelectListItem> list = new List<SelectListItem>();
foreach (Transmission p in lstTrans)
{
list.Add(new SelectListItem() { Value = p.TransmissionText.ToString(), Text = p.TransmissionText.ToString() });
}
return Json(list, JsonRequestBehavior.AllowGet);
}
I have a modal form and it has a text box for entering a new list item. I need to save to the DB, which works but then! I cant come up with the reload the listbox contents part. Any help!
Thanks!
1)Make your code changes like this
success: function (data) {
$('#ListingData_Transmission').html("")
$.each(data, function (index, value) {
$('#ListingData_Transmission').append('<option value="' + value.TransmissionText + '">' + value.TransmissionText + '</option>');
});
}
hope this should work now
2) Make your form as a partial view and reload it whenever your saving something to DB.
Let me know if any issues

Select value in <ul> dropdown , after append <li> from Java script

I have 2 drop down list (ul dropdown) , need to populate 2nd based on first one selection.
here is the full code
<div id="dd" class="wrapper-dropdown-1 brderRad" tabindex="1">
<span>From Any Country</span>
<ul class="dropdown">
#foreach (var country in Model.country_list)
{
<li class="coun" id="#country.country_id">#country.country_name</li>
}
</ul>
</div>
<div id="dd2" class="wrapper-dropdown-1 brderRad" tabindex="1">
<span>From Any City</span>
<ul class="dropdown city_drop" id="city_drop_id">
</ul>
</div>
JS
<script type="text/javascript">
$(document).ready(function () {
$('.coun').click(function () {
var id = ($(this).attr('id'));
$("#city_drop_id").empty();
$.ajax({
url: '#Url.Action("GetCityList", "Home")',
type: 'POST',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify({ id: $(this).attr('id') }),
success: function (data) {
if (data.success) {
var dataa = data.dataDic;
$.each(dataa, function (i, item) {
$('#city_drop_id').append('<li class="selected" value="' + item.ID + '">' + item.Name + '</li>');
});
// $('#city_drop_id').dropdown('refresh');
} else {
alert('Failed');
}
}
});
});
});
</script>
Controller - to retrieve city list based on country selection
[HttpPost]
public JsonResult GetCityList(string id)
{
Dictionary<int, string> cityDic = new Dictionary<int, string>();
cityDic = citydbRep.GetAllCityList().Where(i=>i.city_country_id
==Convert.ToInt32(id)).ToDictionary(t => t.city_id, t => t.city_name);
var dataDic = cityDic.Select(u => new
{
ID = u.Key,
Name = u.Value
});
return Json(new { success = true, dataDic });
}
Now append is working fine, but couldn't able to select the value from 2nd drop down (city ) .
please any one suggest the way to solve this?
Thank you
you need to add cascade drop down. you can achieve this on change function
[yourID].onchange = function () {
}
look this for more detail

Cascading Dropdown Lists in ASP.NET MVC5

I'm working on creating two dropdown lists for a form. The first is a list of Areas and the second needs to filter to the Job Types based on the selected Area.
I'm basing the majority of my code on this answer, but am having trouble getting the Job Types list to show in the View. I can see the correct options being appended when debugging, but am stuck on why they are not populating the Job Type dropdown list.
The View
<!--Area Dropdown-->
#Html.DropDownList("areas", null , new { #class = "col s12 m6 l3" })
<!--Job Type Dropdown-->
#Html.DropDownList("jobType", Enumerable.Empty<SelectListItem>(), "Job Type", new { #class = "col s12 m6 l3" })
The controller code, which is populating my first dropdown box (Area)
var jobArea = (from a in db.tblJobTypes
where a.Active == true
select a.Department).Distinct().ToList();
ViewData["areas"] = new SelectList(jobArea);
The POST action within the controller
[HttpPost]
public ActionResult JobTypeByArea(string area)
{
var test = (from a in db.tblJobTypes
where a.Active == true && a.Department == area
select new
{
id = a.JobTypeID,
job = a.JobType
}).ToList();
return Json(test, JsonRequestBehavior.AllowGet);
}
And finally, the JQuery
$(document).ready(function () {
$('#areas').change(function () {
$.ajax({
url: '/Home/JobTypeByArea',
type: 'POST',
data: { area: $(this).val() },
datatype: 'json',
success: function (data) {
var options = '';
var category = $('#jobType');
$.each(data, function () {
options += '<option value="' + this.id + '">' + this.job + '</option>';
});
$('#jobType').append(options);
},
});
});
});

How to extract and add the JSON data received as a AJAX response to the HTML select drop down using jQuery?

I've following HTML code :
<select id="student" name="student" class="form-control"></select>
The jQuery-AJAX function I've written for adding the options to the above HTML select control is as follows :
var mod_url = $('#mod_url').val();
$.ajax({
url : mod_url,
cache: false,
dataType: "json",
type: "GET",
async: false,
data: {
'request_type':'ajax',
},
success: function(result, success) {
$('#student').html(result);
},
error: function() {
alert("Error is occured");
}
});
From PHP file I've received a big array encoded into JSON format(i.e. the result variable from jQuery-AJAX function). For your reference I'm showing below only the first four records from that array. In HTML select control actually I want to show all the elements from this array.
[{"id":2,"stud_name":"John Dpalma","stud_address1":"277 Eisenhower Pkwy","stud_address2":"","stud_city":"Edison","stud_state":"New Jersey","stud_country":"USA","stud_zipcode":"07039","stud_email":"abc#gmail.com","created_at":1409739580,"updated_at":1410253832},
{"id":3,"stud_name":"Anthony Gonsalvis","stud_address1":"520 Division St","stud_address2":"","stud_city":"Piscataway","stud_state":"NJ","stud_country":"USA","stud_zipcode":"07201","stud_email":"pqr#gmail.com","created_at":1409740530,"updated_at":1410255590},
{"id":4,"stud_name":"James Bond","stud_address1":"6 Harrison Street, 6th Floor","stud_address2":"Ste-2324","stud_city":"New York","stud_state":"NY","stud_country":"USA","stud_zipcode":"10013","stud_email":"xyz#gmail.com","created_at":1409757637,"updated_at":1412263107},
{"id":9,"stud_name":"Mary Jane","stud_address1":"2112 Zeno Place","stud_address2":"CA","stud_city":"Venice","stud_state":"CA","stud_country":"","stud_zipcode":"90291","stud_email":"utp#gmail.com","created_at":1409908569,"updated_at":1410254282}]
In HTML select control I want to set the values in following manner(consider first two records from above array)
<select id="student" name="student" class="form-control">
<option value="">Select Store</option>
<option value="2">John Dpalma, 277 Eisenhower Pkwy, Edison</option>
<option value="3">Anthony Gonsalvis, 520 Division St, Piscataway</option>
</select>
You might have observed from the expected output above that I want to set the value of option as a id from array and the text that I want to display is comprising of stud_name+stud_address1+stud_city
How should I manage this for all the elements from the JSON data in my code?
Also please guide me in showing the loading option into the select control until the response from PHP comes.
Please provide me some help.
success: function(result, success) {
var $select = $('#student');
$.each(result, function (i, option) {
var txt = [option.stud_name, option.stud_address1, option.stud_city];
if (option.stud_address2)
txt.splice(2, 0, option.stud_address2);
$('<option>', {
value: option.id,
text: txt.join(', ')
}).appendTo($select);
});
},
or with $.map (slightly more efficient):
success: function(result, success) {
var options = $.map(result, function (option) {
var txt = [option.stud_name, option.stud_address1, option.stud_city];
if (option.stud_address2)
txt.splice(2, 0, option.stud_address2);
return $('<option>', {
value: option.id,
text: txt.join(', ')
});
});
$('#student').append(options);
},
In PHP file echo the following in a loop:
echo '<option value="">'.$stud_name.', '.$stud_address1.', '.$stud_address2.', '.$stud_city.', '.$stud_state.', '.$stud_country.'</option>';
Then attach this result to the select dropdown with jQuery through the ajax success.
Here is my solution. This checks address 2 and adds it to the options accordingly.
JS code:
for(var i=0;i<result.length;i++){
if(result[i]["stud_address2"]==""){
$('#student').append('<option value="' + result[i]["id"] + '">' + result[i]["stud_name"] + ', ' + result[i]["stud_address1"]+ ', ' +result[i]["stud_city"] +'</option>');}
else{
$('#student').append('<option value="' + result[i]["id"] + '">' + result[i]["stud_name"] + ', ' + result[i]["stud_address1"]+ ', '+ result[i]["stud_address2"]+ ', ' +result[i]["stud_city"] +'</option>');
}
}
Here is a working DEMO
This is exactly what you need!
$(document).ready(function(){
var mod_url = $('#mod_url').val();
$.ajax({
url : mod_url,
cache: false,
dataType: "json",
type: "GET",
async: false,
data: {
'request_type':'ajax',
},
success: function(result, success) {
$.each(result,function(index,item){
$label = item.stud_name +', ' + item.stud_address1 +', ' + item.stud_city;
$('#student').append('<option value="'+ item.id +'">'+ $label +'</option>');
});
},
error: function() {
alert("Error is occured");
}
});
});
It's a matter of iterating over the JSON you receive from the server, creating option tags for each record, then appending them to the select element:
var response = [{"id":2,"stud_name":"John Dpalma" ... }]
$.each(response, function (index, record) {
if (!record.stud_address2){
var stud_address2 = "";
} else {
var stud_address2 = record.stud_address2;
}
$('<option>', {
value: record.id,
text: record.stud_name + ", " + record.stud_address1 + ", " + record.stud_city + ", " + stud_address2
}).appendTo("#student");
});
Demo
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<script>
function __highlight(s, t) {
var matcher = new RegExp("(" + $.ui.autocomplete.escapeRegex(t) + ")", "ig");
return s.replace(matcher, "<strong>$1</strong>");
}
$(document).ready(
function() {
$("#suggest").autocomplete(
{
source : function(request, response)
{
$.ajax({
url : 'URL',
dataType : 'json',
data : { term : request.term },
success : function(data)
{
//alert(data[0].title);
response($.map(data, function(item) {
//alert(item);
return {
label : __highlight(item.title, request.term),
value : item.title
};
}));
}
});
},
minLength : 3,
select : function(event, ui)
{
if(ui.item){
$(event.target).val(ui.item.value);
}
//submit the form
$(event.target.form).submit();
}
}).keydown(function(e) {
if (e.keyCode === 13)
{
$("#search_form").trigger('submit');
}
}).data("autocomplete")._renderItem = function(ul, item)
{
return $("<li></li>").data("item.autocomplete", item).append(
$("<a></a>").html(item.label)).appendTo(ul);
};
});
</script>

Cascading dropdown lists in Mvc 4.0

I have been trying to cascade dropdown lists. For this purpose I am using javascript in .cshtml page . Don't know what is the reason , I'm not able to even call Js method , leave alone the controller method which later needs to be called from within the Js method. Dropdowns are fetching the state and city data but I'm not getting the city according to the state selected.
<div class="editor-label">
#Html.LabelFor(model => model.State_Id)
</div>
<div class="editor-field">
#Html.DropDownList("State",null,"Select State", new {#class="span4", id="State"})
#Html.ValidationMessageFor(model => model.State_Id)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.CityId)
</div>
<div class="editor-field">
#Html.DropDownList("City",null,"Select City", new {#class="span4", id="City"})
#Html.ValidationMessageFor(model => model.CityId)
</div>
<script src="~/Scripts/jquery-1.7.1.js"></script>
<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<script type="text/javascript" >
$(document).ready(function(e) {
$("#State").change(function (e) {
var selectedValue = $(this).val();
if(selectedValue != "Select") {
$.ajax({
url: '#Url.Action("GetCities","Employer")',
type: 'Post',
//data: { "selectedValue": selectedValue},
data: {id: $("#State").val()},
dataType: 'json',
success: function(response) {
var items = "";
$.each(response, function(i, city) {
$("#City").append('<option value="' + city.Value + '">' + city.Text + '</option>');
});
},
error: function (ex) {
alert("Failed To Receive States" + ex);
}
});
}
});
});
</script>
#Html.DropDownListFor(x => x.LeagueId, Model.LeagueSL, "--Select League--", new { id = "ddlLeague"})
#Html.DropDownListFor(x => x.LeagueId, Model.DivisionSL, "--Select Division--", new { id = "ddlDivision"})
The Second DropDownList is empty, all it has is the option Label --Select Division--
On change event of the 1st dropdown make an AjaxRequest that fills the Second One.
var value = $("#DropDown1").val();
var ddlDivision = $("#DropDownDivision");
ddlDivision.html('');//clear current contents;
$.ajax({
url: "/Home/GetDivisions",
type: "GET",
data: { leagueId: value },
success: function (data) {
$.each(data, function (index, item) {
//item = this
//populate ddl
ddlDivision.append($('<option></option>')
.val(item.PropTwo)
.html(item.PropOne));
});
});
public JsonResult GetDivisions(int leagueId)
{
using (BaseballEntities context = new BaseballEntities())
{
var divisions = (from x in context.Table
where x.LeagueID == leagueId
select new
{
PropOne = x.DivisionName,
PropTwo = x.DivisionId
}).ToList();
return Json(divisions, JsonRequestBehavior.AllowGet);
}
}
Edit: As a Side Note it is better to use your Model to fill your dropdownList.
Give your model a SelectList property
public List<SelectListItem> LeagueSL { get; set; }//you will need to initialize in constructor
public ActionResult Index()
{
MyViewModel model = new MyViewModel();
using (MyEntities context = new MyEntities())
{
var leagueList = context.League.ToList();
foreach (var item in leagueList)
{
model.LeagueSL.Add(new SelectListItem() { Text = item.LeagueName, Value = item.LeagueId.ToString() });
}
}
return View(model);
}
Drop down lists are their own beast. You probably need to create the new OPTIONs using standard DOM methods inside the loop rather than jQuery's append method:
success: function(response) {
var items = "", option, $city = $("#City");
$.each(response, function(i, city) {
option = document.createElement("option");
option.value = city.Value;
option.innerHTML = city.Text;
$city.append(option);
});
},

Categories

Resources