How to implement select2.js c# ajax call is not working - c#

Hello I want to load country state and city using select2.js how can i achieve this? i make ajax call to load details of country state and city... i am facing problem when trying to make ajax call to load data using webmethod. BindCountryData and BidnStateData are never called please suggest me solution for that what changes should i do to make call.
$(document).ready(function){
country();
}
function country(){
$(".autosuggest").select2({
minimumInputLength: 1,
placeholder: "Select Item",
allowClear: true,
ajax: {
type: "POST",
url: 'country.aspx/BindCountryData',
async : false,
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: function(term) {
return {
country: term
};
},
results: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.completeName,
slug: item.slug,
id: item.id
}})};}}});}}
$('.autosuggest').change(function () {
searchState();
});
function searchState(){
$(".State").select2({
minimumInputLength: 1,
placeholder: "Select State",
allowClear: true,
ajax: {
type: "POST",
url: 'state.aspx/BidnStateData',
async : false,
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: function(term) {
return {
state: term,
countryId : $('.autosuggest').val()
};
},
results: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.completeName,
slug: item.slug,
id: item.id
}
})
};
}
}
});
}}

I've been using the following approach in my projects:
1) Load select elements at initial stage, and bind onChange action:
<select class="selectcombusca" name="zone_id" onChange="carregacidades($('option:selected',this).val());">
<option value="#">Select State</option>
<option value="1">State 1</option>
<option value="2">State 2</option>
</select>
<select class="selectcombusca" name="cidade_id">
<option value="#">Select City</option>
<option value="1">City 1</option>
<option value="2">City 2</option>
</select>
2) Apply select2 to initial elements:
$(".selectcombusca").select2();
3) Function to load cities based on the selected state, triggered on the select change:
function carregacidades(zone_id) {
$.ajax({
url: your-url,
type: 'post',
dataType: 'json',
data: 'zone_id=' + zone_id, //from the selected option
beforeSend: function() {
$('select[name=\'cidade_id\']').hide();
$('select[name=\'cidade_id\'] + .select2').hide();
//I like to hide the inital element so the user can undestand there's a call being made, avoiding multiple changes on the element.
$('select[name=\'cidade_id\']').after('<span class="loading">Loading Indicator<span>'); //I also like to put some kind of loading indicator, like a spinner
},
complete: function() {
$('.loading').remove(); //remove the loading indicator
$('select[name=\'cidade_id\']').show(); //show DOM element
$("select[name=\'cidade_id\']").select2().val('#'); //rerender select2 and set initial option
$('select[name=\'cidade_id\'] + .select2').show(); //show select2 element
},
success: function(json) {
//create the new options based on the call return
html = '<option value="#">Cidade</option>';
if (json['cidade'] && json['cidade'] != '') {
for (i = 0; i < json['cidade'].length; i++) {
html += '<option value="' + json['cidade'][i]['cityId'] + '">' + json['cidade'][i]['cityName'] + '</option>';
}
}
$('select[name=\'cidade_id\']').html(html); //replace select options on DOM
},
error: function(xhr, ajaxOptions, thrownError) {
//handle error
}
});
};
In short: by changing the select element, I hide the element that will receive the new information, make the call, add then add the information to DOM (still hidden). Finally, rerender the select2 element with the new options and then show it.
I hope this helps you.

Related

Getting text from asp.net dropdownlist which is populated with jquery

I populated asp.net dropdownlists with jquery to show countries and cities. The dropdownlists show the correct value. I need to get the text of a ddlState at the backend of asp.net. However, I cannot get the selected text from the dropdownlist. It said it is null.
Below is my script.
<script type="text/javascript">
$(document).ready(function () {
GetCountries();
GetStates();
});
function GetCountries() {
$.ajax({
type: "GET",
url: "http://api.geonames.org/countryInfoJSON?formatted=true&lang=en&style=full&username=xxx",
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
success: function (data) {
$(".ddlCountry").append($('<option />', { value: -1, text: 'Select Country' }));
$(data.geonames).each(function (index, item) {
$(".ddlCountry").append($('<option />', { value: item.geonameId, text: item.countryName}));
});
},
error: function (data) {
alert("Failed to get countries.");
}
});
}
function GetStates() {
$(".ddlCountry").change(function () {
GetChildren($(this).val(), "States", $(".ddlState"));
});
}
function GetChildren(geoNameId, childType, ddlSelector) {
$.ajax({
type: "GET",
url: "http://api.geonames.org/childrenJSON?geonameId=" + geoNameId + "&username=xxx",
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
success: function (data) {
$(ddlSelector).empty();
$(ddlSelector).append($('<option />', { value: -1, text: 'Select ' + childType }));
$(data.geonames).each(function (index, item) {
$(ddlSelector).append($('<option />', { value: item.geonameId, text: item.name + "," + item.countryCode }));
});
},
error: function (data) {
alert("failed to get data");
}
});
}
</script>
Below is the two dropdownlists that i have.
<asp:DropDownList
runat="server"
ID="ddlCountry"
CssClass="ddlCountry">
</asp:DropDownList>
<br />
<asp:DropDownList
runat="server"
ID="ddlState"
onChange="ddlState_OnChange"
CssClass="ddlState">
</asp:DropDownList>
Can anybody help? Thank you.
your "change" function should not be inside the GetStates() function. You should collect the value every time the user change the select. and after that trigger the GetStates with the actual value.
$(".ddlCountry").change(function () {
valueOfddlCountry = $(this).val();
});

I want to refresh the checkboxes when I am selecting another item from the dropdown

Basically I am assigning roles to the users. I want to automatically show the pre-asssigned roles. I am able to render that on the first time, but the checkboxes remains same when value is changed in dropdown:
type: "POST",
dataType: "json",
url: "/UserRoles/myaction",
data: { "userid": DropDownSelectedVal },
success: function (data) {
$.each(data, function (i, val) {
var a = (data[i]);
$("#" + a).attr('checked', true);
});
},
error: function (error) {
alert('error; ' + eval(error));
}
})
First try to clear all check boxes using the below code on selection change event of dropdown.
$('input:checkbox').removeAttr('checked');
Then run your ajax code for selecting new user roles.
type: "POST",
dataType: "json",
url: "/UserRoles/myaction",
data: { "userid": DropDownSelectedVal },
success: function (data) {
$.each(data, function (i, val) {
$("#" + val).prop('checked', true);
});
},
error: function (error) {
alert('error; ' + eval(error));
}
})
You should control all checkbox. You can try this.
url: "/UserRoles/myaction",
data: { "userid": DropDownSelectedVal },
success: function (data) {
$.each(data, function (i, val) {
var a = (data[i]);
if(!$("#" + a).is(":checked")) {
$("#" + a).attr("checked", true);
}else{
$("#" + a).attr("checked", false);
}
});
},
The elegant solution that I can suggest is to maintain a hidden input to store all your permission that is selected.
Your HTML
<input type="hidden" id="_hiddenSelectedPermissions" value="2, 1" />
<input class="permissions" type="checkbox" value="1">Default Permission 1
<input class="permissions" type="checkbox" value="2">Default Permission 2
<input class="permissions" type="checkbox" value="3">Permission 3
<input class="permissions" type="checkbox" value="4">Permission 4
<input class="permissions" type="checkbox" value="5">Permission 5
Set the hidden control value after ajax results and call below function to reassign all the checked check boxes
function refreshSelectedPermissions() {
$('input:checkbox.permissions').prop('checked', false);
var selected = $('#_hiddenSelectedPermissions').val().split(",") || [];
$('input:checkbox.permissions').each(function() {
var value = $(this).val();
if($.inArray(value, selected) === -1){
$(this).prop('checked', false);
}
else{
$(this).prop('checked', true);
}
});
}

Fetching Cities dynamically in Asp.net HTML control

I have a HTML dropdown list for countries. Now I want to populate the City dropdown accordingly using ajax
<select class="form-control" id="ddCountry" runat="server" tabindex="8"></select>
<select class="form-control" id="ddCity" runat="server" tabindex="9"></select>
<script type="text/javascript">
$('#ddCountry').on('change', function () {
var storeData = { countryId: this.value }
$.ajax({
type: "POST",
url: "UserRegistration.aspx/GetCities",
data: JSON.stringify(storeData),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("The data in list is "+data);
},
error: error
});
});
</script>
My method on .cs page is as follows:
[WebMethod]
public static List<CityBO> GetCities(string countryId)
{
//returning cities
}
The problem is I am able to fetch the data in GetCities method but not able to show it in the ddCity list because it is a HTML control and the method is static, so
ddCity.Items.AddRange(list_of_countries) is not working as ddCity is not being recognized in static method. Please tell how to fill the dropdown list.
You cannot access controls in static method. You need to return list of cities from webmethod and fill dropdown using javascript.In success method of ajax write code like this.
success: function (data) {
fillDropDown(data.d);
}
function fillDropDown(data){
var html = "";
for (var i = 0; i < data.length; i++)
{
html += "<option value='" + data[i].ValueField+ "'>" +
data[i].TextField+ "</option>";
}
$("select[id$=ddlCity]").html(html);
}
You can use ajax success function given below.
success: function (data)
{
var lankanListArray = JSON.parse(data.d);
// running a loop
$.each(lankanListArray, function (index, value)
{
$("#ddlCity").append($("<option></option>").val(this.name).html(this.value));
});
}

Can't serialize Ajax form

I'm trying to make a drop down menu that whenever an option is selected it needs to update a row in a database. I'm creating the drop down menu with this code
Form
using (Ajax.BeginForm("PartialViewName", "admin", null, new AjaxOptions
{
HttpMethod = "Post",
InsertionMode = InsertionMode.Replace,
//LoadingElementId = "LoadingLink",
UpdateTargetId = "PartialViewName"
}, new { id = "connectNewForm" }))
The drop down code
<select name="statusDD" onchange="ChangeStatus(this.value)">
<option value="">Update Status</option>
<option value="1">Open</option>
<option value="2 ">In Progress</option>
<option value="3">Pending</option>
<option value="4">To Be Verified</option>
<option value="5">Approved</option>
<option value="6">Disapproved</option>
<option value="7">Closed</option>
</select>
The ChangeStatus
function ChangeStatus() {
var form = jQuery(".FormID");
var formData = form.serialize();
$.ajax({
url: "/Controller/ActionResult",
data: formData,
cache: false,
error: function (e) {
if (form == null) {
alert("DIDN'T WORK FORM IS NULL");
}
else {
alert("DIDN'T WORK something else");
}
},
success: function (response) {
// A response to say if it's updated or not
alert("worked");
}
});
}
In the controller
public ActionResult UpdateStatus(int id, FormCollection formValues)
{
int ID = util.IntUtilParse(formValues["ID"]);
int newStatus = util.IntUtilParse(formValues["Status"]);
using (var dbContext = new Project.OpenAccess.DataBase())
{
//var swm = dbContext.StoredProcedure(
var swm = dbContext.StoredProcedure(ID, newStatus);
dbContext.SaveChanges();
return PartialView();
}
}
Whenever I select an option it goes through the ajax and then throws an error and never makes it to the controller. I'm very new to Ajax and I'm not sure whats going on.
$.ajax({
url: "/Controller/ActionResult",
data: formData,
cache: false,
Try changing to
$.ajax({
url: 'http://localhost\\:#####/{Controller Name}/UpdateStatus',
data: formData,
type: "POST",
cache: false,
Not 100% on your application logic, but this is why you're not hitting the controller. Note that the placeholder is indicating the name of your controller, since the name of it is not posted. For example if the name is CustomerController then your ajax url will look as such url: 'http://localhost\\:#####/Customer/UpdateStatus'

How to fill a textbox from database when dropdownlist's selected item changed in ASP.NET MVC

I am new to MVC and Javascript. I am trying to make a "change user info" page for admin. I have a dropdown which lists registered users and some textbox for enter various info about users (eg, name, surname). My objective is auto fill textboxes with users current info when selected an user with dropdownlist. But because of MVC is not event driven and doesn't have postback I don't exactly know how to accomplish this. I think I have to trigger a controller method by dropdownlist's onchange and I think the only way is using JS, AJAX or something like these.
Note: I can do all database stuff in Controller.
I have this code so far in my view:
.... #Html.DropDownList("Users", ViewBag.Users as SelectList, "Select a User", new { id="UserId", onchange="userChanged()"} ) ....
.... <script type="text/javascript">
function userChanged() {
}
</script> ....
You can define your controller action method as JsonResult and call it from your jquery using AJAX.
Once you get data using AJAX, you can parse it and fill appropriate textbox with that data.
you can use below code on how to call ajax in you userChanged method:
$.ajax ({
url: '/Controller/Action',
type: 'GET',
async: true,
cache: false,
data: { userId: useridofwhichdatatobefetched},
success: function (result) {
$("#usernametextbox").val = result.userName; }
});
$(document).ready(function(){
$("#UserId").change(function () {
if ($(this).val() != "" && $(this).val() != undefined && $(this).val() != null)
$.ajax({
type: "GET",
url: "/[ControllerName]/[ActionName]/" + $("#UserId").val()
})
.success(function (data) {
// 'data' consits of values returned from controller.
// fill textboxes with values in 'data'
});
});
});
Hope this helps you.
Try something like this (fiddle):
<select id="select1">
<option value="userId1">User 1</option>
<option value="userId2">User 2</option>
<option value="userId3">User 2</option>
</select>
<textarea id="txt1">
</textarea>
$(function(){
$('#select1').change(function(){
$.ajax({
url: "YourAction", // Url.Action()
data: {
userId: $(this).val()
},
success: function(data) {
$('#txt1').val(data);
}
});
});
});

Categories

Resources