cascading drop-down list in mvc 4 - javascript

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

Related

Dynamic DropDownList in ASP.NET MVC NO ACTION RESULT CREATE()

I CANNOT CREATE CASCADING DROPDOWN IN ACTIONRESULT CREATE, ONLY IN ACTION RESULT INDEX IT WORKS
THERE GOES THE CODE
CONTROLLER
public class PessoasController : Controller
{
private GestarkContext db = new GestarkContext();
// GET: Pessoas
public ActionResult Index()
{
ViewBag.Gabinetes = new SelectList(db.Gabinetes, "GabineteId", "Nome");
var pessoageral = db.Pessoas.Include(a => a.gabojecto).Include(a => a.nivelojecto);
return View(pessoageral.ToList());
}
[HttpPost]
public JsonResult getDistricts(int gbtID)
{
List<Departamento> DepartamentoList = db.Departamentoes.Where(p => p.GbtId == gbtID).ToList();
return Json(DepartamentoList, JsonRequestBehavior.AllowGet);
}
VIEW INDEX - IT WORKS HERE
<script>
$(function () {
$('#Gabinetes').change(function () {
var gbtID = $(this).val();
$.ajax({
type: "post",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "getDistricts",
data: "{gbtID:'" + gbtID + "'}",
success: function (data) {
$('#DepartamentoList').empty();
$('#DepartamentoList').append('<option selected="selected" value="">Select Departamento</option>')
$.each(data, function (i, d) {
$('#DepartamentoList').append('<option value=' + d.DircId + '>' + d.Depto + '</option>');
});
},
failure: function (data) {
alert('error occured');
}
});
});
});
</script>
<h2>Lista de Funcioários Registrados</h2>
<br />
<label class="col-md-2 control-label">Gabinete</label>
<div class="col-md-5">
#Html.DropDownList("Gabinetes", null, htmlAttributes: new { #class = "form-control" })
</div>
<div class="form-group">
<label class="col-md-2 control-label">Departamento</label>
<div class="col-md-4">
<select id="DepartamentoList" name="DepartamentoList" class="form-control"></select>
</div>
</div>
<p>
#Html.ActionLink("Visualizar Formulário", "Index", "Principal", null, new { #class = "btn btn-default" }) | #Html.ActionLink("Adicionar Novo", "Create", null, new { #class = "btn btn-primary" }) | #Html.ActionLink("Exportar em Excel", "ExportToExcel", null, new { #class = "btn btn-success" })
</p>
...........
NOW ON VIEW CREATE DOES NOT WORK
I write the code as I do in index, but it doesn't work
I NEED YOUR HELP PLEASE

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

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>

Jquery not working in modal popup ASP.NET MVC

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?

Categories

Resources