Ajax request does not work on a cascading dropdown value change - javascript

Hi I have a cascading drop-down and on it's change I have a requirement to populate another field by getting it's value from the database.
unfortunately when I try to populate the drop-down my ajax always responds an error 500. I don't know what is wrong with it.
I am using this tutorial as my guide.
Here is my Javascript
<script>
$(function () {
$('#selectedExperience_ExpertiseID').change(function () {
var selectedExpertise = $('#selectedExperience_ExpertiseID :selected').val();
selectedExpertise = selectedExpertise == "" ? 0 : selectedExpertise;
//When select 'optionLabel' we need to reset it to default as well. So not need
//travel back to server.
if (selectedExpertise == "") {
$('#selectedExperience_FunctionID').empty();
$('#selectedExperience_FunctionID').append('<option value="">--Select a language--</option>');
return;
}
//This is where the dropdownlist cascading main function
$.ajax({
type: "GET",
url: "GetFunctionByID", //Your Action name in the DropDownListConstroller.cs
async: false,
data: { selectedExpertise: selectedExpertise }, //Parameter in this function, Is cast sensitive and also type must be string
contentType: "application/json; charset=utf-8",
dataType: "json"
}).done(function (data) {
//When succeed get data from server construct the dropdownlist here.
if (data != null) {
$('#selectedExperience_FunctionID').empty();
$.each(data.function, function (index, data) {
$('#selectedExperience_FunctionID').append('<option value="' + data.Value + '">' + data.Text + '</option>');
});
}
}).fail(function (response) {
if (response.status != 0) {
alert(response.status + " " + response.statusText);
}
});
});
});
</script>
and here is my HTML
<div class="form-group">
#Html.LabelFor(model => model.selectedExperience.ExpertiseID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.selectedExperience.ExpertiseID, Model.expertise, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.selectedExperience.ExpertiseID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.selectedExperience.FunctionID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.selectedExperience.FunctionID, Model.function, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.selectedExperience.FunctionID, "", new { #class = "text-danger" })
</div>
</div>
Please help me. I am stuck in this functionality for 4 days now.
point me to the right direction.
Thanks!

i think your ajax is not sending any data because of this
data: { selectedExpertise: selectedExpertise }
change it to
data: { 'selectedExpertise': selectedExpertise }
i think there should be a quote around the object name

Firstly , give id to both the dropdownlists,I didnt find selectedExperience_ExpertiseID and check the $.each function result
Also,I have modified bit of html. Kindly try this code. Hope your method GetFunctionByID is working well.I have take table and its column according to my reference db.
<script type="text/javascript">
$(function () {
$('#selectedExperience_ExpertiseID').change(function () {
var selectedExpertise = $('#selectedExperience_ExpertiseID :selected').val();
selectedExpertise = selectedExpertise == "" ? 0 : selectedExpertise;
//When select 'optionLabel' we need to reset it to default as well. So not need
//travel back to server.
if (selectedExpertise == "") {
$('#selectedExperience_FunctionID').empty();
$('#selectedExperience_FunctionID').append('<option value="">--Select a language--</option>');
return;
}
//This is where the dropdownlist cascading main function
$.ajax({
type: "GET",
url: "/DropDownList/GetFunctionByID", //Your Action name in the DropDownListConstroller.cs
async: false,
data: { stateId: selectedExpertise }, //Parameter in this function, Is cast sensitive and also type must be string
contentType: "application/json; charset=utf-8",
dataType: "json"
}).done(function (data) {
//When succeed get data from server construct the dropdownlist here.
if (data != null) {
$('#selectedExperience_FunctionID').empty();
$.each(data, function (key, val) {
$('#selectedExperience_FunctionID').append('<option value="' + val.value + '">' + val.Text + '</option>');
});
}
}).fail(function (response) {
if (response.status != 0) {
alert(response.status + " " + response.statusText);
}
});
});
});
</script>
#model WebApplication6.Models.StudentModel
#{
ViewBag.Title = "Index";
}
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<div class="form-group">
#Html.Label("Expertise", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.StateNames, Model.StateNames, new { #class = "form-control", #id = "selectedExperience_ExpertiseID" })
#Html.ValidationMessageFor(model => model.StateNames, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.Label("Function", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.DistrictNames, new List<SelectListItem>(), new { #class = "form-control", #id = "selectedExperience_FunctionID" })
#Html.ValidationMessageFor(model => model.DistrictNames, "", new { #class = "text-danger" })
</div>
</div>

Related

Dropdown list return always default value 0

I have problem. When i didn't search something in dropdown It has got default selected value=0. And its saving my database. If it can send value"NULL" not will save in my database. How can i send default value "NULL"?
<div class="form-group">
<label class="control-label col-md-2"></label>
<div class="col-md-8">
#*#Html.DropDownList("CustomerID", null, new { #class = "form-control", required = "required", placeholder = "Müşteri Seçiniz" })*#
#Html.DropDownList("CustomerID", Enumerable.Empty<SelectListItem>(), "", new { #multiple = "multiple", #id = "CustomerID", #class = "form-control" })
#Html.ValidationMessageFor(model => model.CustomerID, "", new { #class = "text-danger", style="color:red"})
<p style="color:red;margin-bottom:-3px" id="errorpersonel"></p>
</div>
</div>
<script language="javascript" type="text/javascript">
$(document).ready(function () {
debugger;
$("#CustomerID").pqSelect({
singlePlaceholder: '', width: '92%'
});
$.ajax({
url: "/TicketDashboard/GetCustomer",
method: "Post",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#CustomerID").empty();
$.each(data, function (index, value) {
debugger;
$('#CustomerID').append('<option value="' + value.CustomerID + '">' + value.CustomerName + '</option>');
});
$("#CustomerID").pqSelect("refreshData");
$('span[data-valmsg-for="OpportunityAttachmentViewModel.CCMail"]').html('Boş geçilemez.');
}
});
});
$("#CustomerID").pqSelect({
singlePlaceholder: '',
multiplePlaceholder: 'Müşteri Seçiniz',
maxSelect: 1,
}).on("change", function (evt) {
pccmail = $(this).val();
if (pccmail != "") {
$('span[data-valmsg-for="OpportunityAttachmentViewModel.CCMail"]').html('');
} else {
$('span[data-valmsg-for="OpportunityAttachmentViewModel.CCMail"]').html('Boş geçilemez');
}
$('[id^=CCMailinput]').val(pccmail);
});
Its my codes. How can i change selected value "0"? It should be "NULL" when i sent form
You can choose a null value as below if the selected value is 0.
pccmail = $(this).val()=="0"?null:(this).val();
<div class="form-group">
<label class="control-label col-md-2"></label>
<div class="col-md-8">
#*#Html.DropDownList("CustomerID", null, new { #class = "form-control", required = "required", placeholder = "Müşteri Seçiniz" })*#
#Html.DropDownList("CustomerID", Enumerable.Empty<SelectListItem>(), "", new { #multiple = "multiple", #id = "CustomerID", #class = "form-control" })
#Html.ValidationMessageFor(model => model.CustomerID, "", new { #class = "text-danger", style="color:red"})
<p style="color:red;margin-bottom:-3px" id="errorpersonel"></p>
</div>
</div>
<script language="javascript" type="text/javascript">
$(document).ready(function () {
debugger;
$("#CustomerID").pqSelect({
singlePlaceholder: '', width: '92%'
});
$.ajax({
url: "/TicketDashboard/GetCustomer",
method: "Post",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#CustomerID").empty();
$.each(data, function (index, value) {
debugger;
$('#CustomerID').append('<option value="' + value.CustomerID + '">' + value.CustomerName + '</option>');
});
$("#CustomerID").pqSelect("refreshData");
$('span[data-valmsg-for="OpportunityAttachmentViewModel.CCMail"]').html('Boş geçilemez.');
}
});
});
$("#CustomerID").pqSelect({
singlePlaceholder: '',
multiplePlaceholder: 'Müşteri Seçiniz',
maxSelect: 1,
}).on("change", function (evt) {
pccmail = $(this).val()=="0"?null:(this).val();
if (pccmail != "") {
$('span[data-valmsg-for="OpportunityAttachmentViewModel.CCMail"]').html('');
} else {
$('span[data-valmsg-for="OpportunityAttachmentViewModel.CCMail"]').html('Boş geçilemez');
}
$('[id^=CCMailinput]').val(pccmail);
});

How can I get my jquery autocomplete to fill in multiple fields in MVC?

I am trying to setup an autocomplete in jquery that gets information from a user in Active Directory. A user can type in a few letters of a person's last name, and what returns is a 2D list (List>) that contains all the people whose last name starts with those letters. Each List holds the first, middle, last name and AD name of a person. And of course, each List> element represents a person.
I have no issues getting the data in jquery. The problem is that I can't seem to figure out how to make it populate the Employee_Name and Employee_Name_AD fields with the information in this array once the user clicks on a name from the list. This is my jquery code:
#section page {
<script type="text/javascript">
$(document).ready(function () {
var name;
var adname;
$("#TESTING").autocomplete(
{
source: function (request, response) {
$.ajax({
url: "/Employees/GetUserList",
type: "POST",
dataType: "json",
data: { query: request.term },
success: function (data) {
response($.map(data, function (item) {
name = item[0] + " " + item[1] + " " + item[2];
adname = item[3];
return { label: name, data: [name, adname] };
}))
},
select: function (event, ui) {
$('#Employee_Name').val(ui.data.item.data[0]);
$('#Employee_Name_AD').val(ui.data.item.data[1]);
}
})
},
});
})
</script>
}
And on the same page, here is the accommodating Razor code:
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Employee</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<div class="col-md-10">
#Html.TextBox("TESTING")
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Employee_Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Employee_Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Employee_Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Employee_Name_AD, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Employee_Name_AD, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Employee_Name_AD, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
I found something super close to what I want thanks to stack overflow: http://jsbin.com/vasuliru/2/edit?html,js,output
The problem with the previous example is that the data is declared on the page itself, not pulled from a data source. How can I modify my code to get it to do what I want?
I was finally about to find a solution, after I came across something in php: Jquery ui autocomplete on multiple input fields with ajax results.
My final code is this:
#section page {
<script type="text/javascript">
$(document).ready(function () {
var name;
var adname;
$("#UserLookup").autocomplete(
{
source: function (request, response) {
$.ajax({
url: "/Employees/GetUserList",
type: "POST",
dataType: "json",
data: { query: request.term },
success: function (data) {
response($.map(data, function (item) {
name = item[0] + " " + item[1] + " " + item[2];
adname = item[3];
console.log(adname);
return { label: name, data: item }
}));
}
});
},
select: function (event, ui) {
console.log(ui.item);
$(this).val(ui.item.label);
var userid = ui.item.value;
console.log("Here is the userid:");
console.log(item);
console.log(ui.item.data[3]);
$('#Employee_Name').val(ui.item.value);
$('#Employee_Name_AD').val(ui.item.data[3]);
}
});
});
</script>
}

change event not perform on datepicker through jquery

I want to pass a selected date to controller for performing operation on database.
But my jquery is not functioning properly..
Can anyone help me solve the issue?
here is my View code :
<div class="form-group">
#Html.EditorFor(model => model.DT, new { htmlAttributes = new { #class = "form-control datepicker", placeholder = "PRC Date", Value = DateTime.Now.ToShortDateString() } })
#Html.ValidationMessageFor(model => model.DT, "", new { #class = "text-danger" })
</div>
here is my jQuery Code..
$("#DT").on("change", function () {
debugger
var selectedValue = $(this).val();
alert(selectedValue);
$.ajax({
type: "POST",
url: '#Url.Action("DateWiseData", "ProcessWax")',
contentType: "application/json; charset=utf-8",
data: selectedValue,
dataType: "json",
success: function (data) {
if (data.status == true) {
alert('Successfully done.');
}
else {
alert('Failed');
}
},
//error: function () { alert('Error. Please try again.'); }
});
});
HTML:
<div class="form-group">
#Html.TextBoxFor(model => model.DT, new { htmlAttributes = new { #class = "form-control datepicker", placeholder = "PRC Date", Value = DateTime.Now.ToShortDateString() } })
</div>
jquery:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
alert();
$("#DT").on("change", function () {
var selectedValue = $(this).val();
alert(selectedValue);
$.ajax({
type: "POST",
url: "/ProcessWax/DateWiseData?Date=" + selectedValue ,
contentType: "application/json; charset=utf-8",
data: selectedValue,
dataType: "json",
success: function (data) {
if (data.status == true) {
alert('Successfully done.');
}
else {
alert('Failed');
}
},
//error: function () { alert('Error. Please try again.'); }
});
});
</script>
Controller:
[HttpPost]
public ActionResult DateWiseData(DateTime Date)
{
}
If you want that select a date from Jquery datepicker and send it to your controller you can simply bind your datepicker to your controller.
HTML :
#using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
<div class="form-group">
#Html.EditorFor(model => model.DT, new { htmlAttributes = new { #class = "form-control datepicker", placeholder = "PRC Date", Value = DateTime.Now.ToShortDateString() } })
#Html.ValidationMessageFor(model => model.DT, "", new { #class = "text-danger" })
</div>
<button type="submit"></button>
}
Controller :
[HttpPost]
public ActionResult Index(YourModel t)
{
var date = t.DT;
//Do whatever you want (ex. save in database)
return View();
}
UPDATE:
Please Try this code:
$( function() {
$( "#DT" ).datepicker()
.on("change", function () {
var selectedValue = $(this).val();
alert(selectedValue);
$.ajax({
type: "POST",
url: '#Url.Action("DateWiseData", "ProcessWax")',
contentType: "application/json; charset=utf-8",
data: selectedValue,
dataType: "json",
success: function (data) {
if (data.status == true) {
alert('Successfully done.');
}
else {
alert('Failed');
}
}
});
});
} );
As you can see in the code you forgot to put .datepicker() after $("#DT") .

Jquery Ajax call does not call Asp.net mvc controller action method

I have two drop-downs State and City.According to State selected city should be loaded.So I use State drop-down change event to call ajax method to populate City drop-down.
HTML
<div class="row">
<div class="col-sm-6 ">
<div class="form-group">
<label>State</label>
#Html.DropDownListFor(m => m.State, Model.States, "Please select a State", new { #class = "form-control" })
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6 ">
<div class="form-group">
<label>Cities</label>
#Html.DropDownListFor(m => m.CityRegisterScreen, new SelectList(string.Empty, "Id", "Name"), "Please select a city", new { #class = "form-control" })
</div>
</div>
</div>
JavaScript
This Contains Jquery and Javascript Code.
$(document).ready(function () {
$("#State").on("change", function () { // whenever a selection is made
$("#CityRegisterScreen").empty();
var id = $("#State").val();
$.ajax({
type: 'GET', // we are calling json method
url: '#Url.Action("GetCitiesByDistrict", "Account")',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: { id: id },
success: function (cities) {
$.each(cities, function (i, city) {
$("#CityRegisterScreen").append('<option value="' + city.value + '">' +
city.Text + '</option>');
});
},
error: function (ex) {
alert('Failed to retrieve cities.' + ex);
}
});
return false;
});
});
Controller
This is the controller action method which returns Json
public JsonResult GetCitiesByDistrict(int id)
{
List<SelectListItem> cities = new List<SelectListItem>();
var city = new List<City>();
using (ApplicationDbContext context = new ApplicationDbContext())
{
city = context.Cities.Where(e => e.DistrictId == id).ToList();
}
return Json(new SelectList(city, "Id", "Name"), JsonRequestBehavior.AllowGet);
}
Issue is when ajax method is called it doesn't call the Action method in controller.I double checked the URL and DataType it's all perfect.But Action method didn't get called.
It is silly!!! How did i miss this. Thank You #Rajshekar Reddy for your comment it guided me. I am missing [AllowAnonymous] attribute.
[AllowAnonymous]
public JsonResult GetCitiesByDistrict(int id)
{
List<SelectListItem> cities = new List<SelectListItem>();
var city = new List<City>();
using (ApplicationDbContext context = new ApplicationDbContext())
{
city = context.Cities.Where(e => e.DistrictId == id).ToList();
}
return Json(new SelectList(city, "Id", "Name"), JsonRequestBehavior.AllowGet);
}
This is a code for loading States according to selected country. Try this solution.
HTML
#Html.DropDownListFor(model => model.CustAddr_Country_ID, Model.Countries, "Select Country", htmlAttributes: new { #class = "disableInput", #id = "ddlstate", #onchange = "javascript:GetCity(this.value);" })
#Html.DropDownListFor(model => model.CustAddr_State_ID, ViewBag.CustAddr_State_ID as SelectList, "Select State", htmlAttributes: new { #class = "disableInput"})
Script
function GetCity(_stateId) {
$("#CustAddr_State_ID").empty().trigger('change');
var newOption = new Option("Select State", 0, true, true);
$("#CustAddr_State_ID").append(newOption).trigger('change');
if (_stateId != null && _stateId != "") {
var url = "/Ajax/GetCityByStaeId/";
$.ajax({
url: url,
data: { stateid: _stateId },
cache: false,
type: "POST",
success: function (data) {
for (var x = 0; x < data.length; x++) {
var newOption = new Option(data[x].Text, data[x].Value, true, true);
$("#CustAddr_State_ID").append(newOption).trigger('change');
}
$('#CustAddr_State_ID').val('0').trigger('change');
},
error: function (reponse) {
//alert("error : " + reponse);
}
});
}
}
Controller
[HttpPost]
public ActionResult GetCityByStaeId(int stateid)
{
List<State> objcity = new List<State>();
objcity = _state.GetState().Where(m => m.State_Country_ID == stateid).ToList();
SelectList obgcity = new SelectList(objcity, "State_ID", "State_Name", 0);
return Json(obgcity);
}

cascading drop-down list in mvc 4

I created cascading drop-down list as shown in the picture
here the view
here the cshtml code snippet
<div class="form-group">
<div class="editor-label">
#Html.LabelFor(model => model.HEI_ID)
#Html.Label("*", new { id="star" , #class = "requiredFiledCol" })
</div>
<div class="editor-field">
#Html.DropDownListFor(m => m.HEI_ID, (SelectList)ViewBag.UniversityList_New, "Select University / Institute", new {id="University", #class = "form-control" })
#Html.ValidationMessageFor(model => model.HEI_ID)
</div>
</div>
<div class="form-group">
<div class="editor-label">
#Html.LabelFor(model => model.COL_ID)
#Html.Label("*", new { id="star" , #class = "requiredFiledCol" })
</div>
<div class="editor-field">
#Html.DropDownListFor(m => m.COL_ID, (SelectList)ViewBag.FacultyList_New, "Select College", new {id="College", #class = "form-control" })
#Html.ValidationMessageFor(model => model.COL_ID)
</div>
</div>
<div class="form-group">
<div class="editor-label">
#Html.LabelFor(model => model.DEP_ID)
#Html.Label("*", new { id="star" , #class = "requiredFiledCol" })
</div>
<div class="editor-field">
#Html.DropDownListFor(m => m.DEP_ID, (SelectList)ViewBag.DepartmentList_New, "Select Department", new { id="Department" , #class = "form-control" })
#Html.ValidationMessageFor(model => model.DEP_ID)
</div>
</div>
This is jquery code snippet
<script type="text/javascript">
$(document).ready(function () {
//Dropdownlist Selectedchange event
$("#University").change(function () {
$("#College").empty();
$("#Department").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("GetColleges")', // we are calling json method
dataType: 'json',
data: { uni_id: $("#University").val() },
success: function (Colleges) {
$.each(Colleges, function (i, state) {
$("#College").append('<option value="' + state.Value + '">' + state.Text + '</option>');
});
},
error: function (ex) {
alert('Failed to retrieve states.' + ex);
}
});
return false;
})
$("#College").change(function () {
$("#Department").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("GetDepartments")', // we are calling json method
dataType: 'json',
data: { col_id: $("#College").val() },
success: function (Departments) {
$.each(Departments, function (i, state) {
$("#Department").append('<option value="' + state.Value + '">' + state.Text + '</option>');
});
},
error: function (ex) {
alert('Failed to retrieve states.' + ex);
}
});
return false;
})
});
But in last dropdown (department drop down) its not populate , how can I overcome this
this is the action methods related to this module
public JsonResult GetColleges(string uni_id)
{
var Colleges = from college in db.Colleges
where college.HEI_ID == uni_id & college.Status == true
select college;
//List<SelectListItem> states = new List<SelectListItem>();
return Json(new SelectList(Colleges.ToList(), "College_ID", "College_Name"));
}
public JsonResult GetDepartments(string col_id)
{
var Departments = from department in db.Departments
where department.College_ID == col_id & department.Status == true
select department;
//List<SelectListItem> states = new List<SelectListItem>();
return Json(new SelectList(Departments.ToList(), "Department_ID", "Name_of_Department"));
}
I tried out your code and it is working for me fine but not when you have only one item returned and populated in the College dropdown. That is because change() will not be fired if you have only 1 item and you select that. So to avoid what you can do is when cascade load data in dropdown add a option label so that user has to select a valid option and change gets fired and thus, Department dropdown get loaded with data. So your College change can look like this:
$("#College").change(function () {
$("#Department").empty();
//If option label was selected then do not send request
if ($("#College").val() == 0)
{
return;
}
$.ajax({
type: 'POST',
url: '#Url.Action("GetDepartments")',
dataType: 'json',
data: {
col_id: $("#College").val()
},
success: function (Departments) {
//Add option label as the first element (selected by default)
$("#Department").append('<option value="0">-SELECT COLLEGE-</option>');
$.each(Departments, function (i, state) {
$("#Department").append('<option value="' + state.Value + '">' + state.Text + '</option>');
});
},
error: function (ex) {
alert('Failed to retrieve states.' + ex);
}
});
return false;
});
NOTE: Changes indicated with comment above code

Categories

Resources