Jquery not working in modal popup ASP.NET MVC - javascript

I have a modal popup that I want to use some cascading drop down lists in.
The drop downs work fine when I render the page as a regular view but when I render it as a partial in a modal popup I lose the functionality.
The script doesn't seem to run at all now.
Here is the code that should run when a drop down value is selected:
$("#artistSelect").change(function () {
if ($(this).val() != "") {
$("#pieceSelect").empty();
$("#productSelect").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("GetMasterImages")',
dataType: 'json',
data: {
artistId: $(this).val()
},
success: function (masterImages) {
$(masterImages).each(function (i, masterImage) {
$("#pieceSelect").append('<option value="' + masterImage.Value + '">' + masterImage.Text + '</option');
});
$("#productSelect").append('<option value="">-- Select Piece --</option>');
},
error: function (ex) {
alert('failed to get piece list.' + ex);
}
});
} else {
$("#pieceSelect").empty();
$("#productSelect").empty();
$("#productSelect").append('<option value="">-- Select Artist --</option>');
$("#pieceSelect").append('<option value="">-- Select Artist --</option>');
}
return false;
});
$("#pieceSelect").change(function () {
if ($(this).val() != "") {
$("#productSelect").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("GetProducts")',
dataType: 'json',
data: {
imageMasterId: $(this).val()
},
success: function (products) {
$(products).each(function (i, product) {
$("#productSelect").append('<option value="' + product.Value + '">' + product.Text + '</option');
});
},
error: function (ex) {
alert('failed to get product list.' + ex);
}
});
} else {
$("#productSelect").empty();
$("#productSelect").append('<option value="">-- Select Piece --</option>');
}
return false;
});
The scripts are located in my main scripts file.
and my now partial view:
<div class="form-group">
<div class="row">
<div class="col-md-3">
#Html.DropDownList("Artist", Model.Dropdowns.ArtistItems, new { #id = "artistSelect", #class = "form-control" })
</div>
<div class="col-md-3">
#Html.DropDownList("Piece", new List<SelectListItem> { new SelectListItem { Text = "-- Select Artist --", Value = "" } }, new { #id = "pieceSelect", #class = "form-control" })
</div>
<div class="col-md-3">
#Html.DropDownListFor(m => m.CustomerItem.ItemID, new List<SelectListItem> { new SelectListItem { Text = "-- Select Artist --", Value = "" } }, new { #id = "productSelect", #class = "form-control" })
</div>
</div>
Why do my cascading drop downs no longer work?

Related

Dropdown search doesn't work on modal in paramquery

I'm using a modal and when I try to use my dropdown search it doesn't work, but it works in a normal page.
How can I make it work in the modal? I should be able to search customer name in dropdown.
<div class="form-group">
<label class="control-label col-md-2"></label>
<div class="col-md-8">
#Html.DropDownList("CustomerID", Enumerable.Empty<SelectListItem>(), null, new { #multiple = "multiple", #id = "CustomerID", #class = "form-control" })
</div>
</div>
$(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);
});

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);
}

Ajax request does not work on a cascading dropdown value change

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>

Need Help while Populating the DropDownList via Java Script from MVC. List not populating

I am facing the problem when I am populating the DropDownList by JavaScript via MVC. I am getting the Uncaught TypeError: Cannot read property 'length' of undefined while populating the DDL.
My Code as define below
View:-
<div class="form-group">
<label>SubRetailer</label>
#Html.DropDownListFor(m => m.SubRetailer, Model.SubRetailerList, "All Selected", new { #class = "form-control", id = "SubParentRetailerDDL" })
</div>
Controller : -
public ActionResult getSubRetailer(int ParentRetailerID)
{
List<DashboardGetSubRetailer_Result> lstDesig = db.DashboardGetSubRetailer(ParentRetailerID).ToList();
return Content(JsonConvert.SerializeObject(lstDesig), "application/json");
}
JavaScripts function:-
function GetNames(ParentRetailerID) {
if (ParentRetailerID > 0) {
$("#SubParentRetailerDDL").get(0).options.length = 0;
$("#SubParentRetailerDDL").get(0).options[0] = new Option("Loading SubRetailer", "-1");
alert("ParentRetailerID : "+ ParentRetailerID);
$.ajax({
type: "POST",
url: "Search/getSubRetailer",
data: "{ParentRetailerID:" + ParentRetailerID + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("success : " + ParentRetailerID);
$("#SubParentRetailerDDL").get(0).options.length = 0;
$("#SubParentRetailerDDL").get(0).options[0] = new Option("Select SubRetailerName", "-1");
**$.each(msg.d, function (index, item) {
$("#SubParentRetailerDDL").get(0).options[$("#SubParentRetailerDDL").get(0).options.length] = new Option(item.SubRetailerName, item.SubRetailerID);
});
},**
error: function () {
alert("error : " + ParentRetailerID);
$("#SubParentRetailerDDL").get(0).options.length = 0;
alert("Failed to load SubRetailer");
}
});
}
else {
$("#SubParentRetailerDDL").get(0).options.length = 0;
}
}
I am facing the error at below step in java script. I am getting the data from Controller but not populating in DDL.
$.each(msg.d, function (index, item) {
$("#SubParentRetailerDDL").get(0).options[$("#SubParentRetailerDDL").get(0).options.length] = new Option(item.SubRetailerName, item.SubRetailerID);
});
I do not know what you are trying to do with that line. But if you are trying to replace the options of your second dropdown with the data coming from the server, you can simply do this.
$("#SubParentRetailerDDL").html(""); //Clear existing items
//loop through the items came back and append to dropdown
$.each(msg, function (index, item) {
$("#SubParentRetailerDDL")
.append("<option value='"+item.SubRetailerID+"'>"+item.SubRetailerName+"</option>");
});
Also there is no reason for you to explicitly Serialize the data to json format because there is already a Json method which does that for you.
public ActionResult getSubRetailer(int ParentRetailerID)
{
var data = db.DashboardGetSubRetailer(ParentRetailerID).ToList();
return Json(data , JsonRequestBehavior.AllowGet);
}
This code will work assuming your DashboardGetSubRetailer method returns a collection of items each with a SubRetailerID and a SubRetailerName property. If you have a single property called d which the collection, just udpate the $.each(msg with $.each(msg.d
Its working now as below
Changes in View--
<div class="form-group">
<label>Retailer</label>
#Html.DropDownListFor(m => m.Retailer, new SelectList(Model.lstParentRetailsDetails, "ParentRetailerID", "ParentRetailerName"), "All Selected", new { id = "ParentRetailerDDL", #class = "form-control" })
</div>
<div class="form-group">
<label>SubRetailer</label>
#Html.DropDownListFor(m => m.SubRetailer, new SelectList(Enumerable.Empty<SelectListItem>(), "SubRetailerID", "SubRetailerName"), "All Selected", new { #class = "form-control", id = "SubParentRetailerDDL" })
</div>
-- Inside Java Scripts
$().ready(function (msg) {
$("#ParentRetailerDDL").bind("change", function () {
GetNames($(this).val());
});
});
function GetNames(ParentRetailerID) {
if (ParentRetailerID > 0) {
$("#SubParentRetailerDDL").empty();
$.ajax({
type: "POST",
url: "Search/getSubRetailer",
data: "{ParentRetailerID:" + ParentRetailerID + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$.each(msg, function (index, item) {
$("#SubParentRetailerDDL").append("<option value='" + item.SubRetailerID + "'>" + item.SubRetailerName + "</option>");
});
},
error: function () {
$("#SubParentRetailerDDL").get(0).options.length = 0;
alert("Failed to load SubRetailer");
}
});
}
else {
$("#SubParentRetailerDDL").get(0).options.length = 0;
}
}

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