How to get data to DropDownList based on other dropdown? - asp.net-mvc

I have a table (dept) on database and fields are:
1 - id
2 - Division
3 - Designation
I am retrieving division data on dropdown, this is my code:
public JsonResult GetDivision()
{
var division = db.Depts.GroupBy(x => x.Division)
.Select(x => x.FirstOrDefault()).OrderBy(x => x).ToList();
return Json(division);
}
Now I want to get the designation data on 2nd dropdown based on division name
public JsonResult GetDesignation(int StateId)
{
var department = db.Depts.Where(x => x.DeptId == StateId)
.OrderBy(x => x.Designation);
return Json(department);
}
Ajax code:
$(document).ready(function () {
$('#division').change(function () {
$('#designation').empty();
$.ajax({
type: "POST",
url: "/Official/GetDesignation",
datatype: "Json",
data: { StateId: $('#division').val() },
success: function (data) {
$('#designation').append('<option value>--Select--</option>');
$.each(data, function (index, value) {
$('#designation').append('<option value="' + value.deptId + '">' + value.designation + '</option>');
console.log(value);
});
}
});
});
html:
#Html.DropDownList("division", new SelectList(string.Empty, "Value", "Text"), "--Select--", null)
#Html.DropDownList("designation", new SelectList(string.Empty, "Value", "Text"), "--Select--", null)
When I select divison from dropdown, I get only one designation, which is getting from id, but I want to get all designation based on division name for exmaple I have this type of data
id division designation
1 CORPORATE AFFAIRS Manager Corporate Affairs
2 CORPORATE AFFAIRS Manager BPR & PMO
3 CORPORATE AFFAIRS Jr. Executive Corporate Governance
in 1st dropdown I am getting one "corporate affairs", but when I select "corporate affairs" I need to get all designation in 2nd dropdown

Ok, I think you need to understand the following...
This line here:
var department = db.Depts.Where(x => x.DeptId == StateId)
.OrderBy(x => x.Designation);
Is making a SQL query at the end, which will traduce into something like:
SELECT * FROM Depts WHERE DeptId = Something ORDER BY Designation
I assume that DeptId is a PRIMARY KEY, which is a unique value on the table, when you process the query above it will bring only one or zero results depending on if there is a match.
I think you should correct the value that you are passing from the ajax POST, you could use:
data: { StateId: $('#division').text() }
instead of:
data: { StateId: $('#division').val() }
This way you are passing the Division name as string and modify your function as follows:
public JsonResult GetDesignation(string Division)
{
var department = db.Depts.Where(x => x.Division == Division)
.OrderBy(x => x.Designation);
return Json(department);
}

Related

Populate second Droplist depending on values of first Droplist

How can I change the selection of a second drop down list depending on the first selected dropdown value? For example in the code below if the listDepartments is "Sales" I only want the choice for listCatagory droplist to be Customers, and when selecting HR I only want the choice to be "Resumes" Is this possible with the code below or do I need a new approach, and if so is there a good example somewhere?
Thanks,
EB
List<SelectListItem> listDepartments = new List<SelectListItem>();
listDepartments.Add(new SelectListItem
{
Text = "Sales",
Value = "Sales",
});
listDepartments.Add(new SelectListItem
{
Text = "HR",
Value = "HR"
});
List<SelectListItem> listCatagory = new List<SelectListItem>();
listCatagory.Add(new SelectListItem
{
Text = "Customers",
Value = "Customers",
});
listCatagory.Add(new SelectListItem
{
Text = "Resumes",
Value = "Resumes",
});
When selecting the department is does nothing.
OK I added this to my controller:
public JsonResult GetCategory(int id)
{
var department = db.Documents.Where(t => t.ID == id).FirstOrDefault();
return Json(new SelectList(db.Catagories.Where(t => (t.Department == department.Department)), "Category", "Text"));
}
But I am not sure where it get the data for data: { id: $("#droplist_Departments_ID").val() }, from??
Do I need to change way the droplist is for the departments?
listDepartments.Add(new SelectListItem
{
Text = "Customer Service",
Value = "CustomerService",
You'll have to use Javascript in order to make an Ajax request passing the previous droplist selected item to a method in the controller which will return a SelectList, something like this:
$.ajax({
type: 'POST',
url: 'GetCategory',
dataType: 'json',
data: { id: $("#droplist_Departments_ID").val() },
success: function (mems) {
// states contains the JSON formatted list
// of states passed from the controller
$.each(mems, function (i, member) {
$("#droplist_Category_ID").append('<option value="' + member.Value + '">' + member.Text + '</option>');
});
},
error: function (ex) {
console.log('Failed to retrieve states. Exception: ' + ex);
}
});
In the controller something like (adapt to your db schema, obviously):
public JsonResult GetCategory(int id)
{
var department = db.Departments.Where(t => t.Id == id).FirstOrDefault();
return Json(new SelectList(db.Categories.Where(t => (t.DepartmentId == department.Id)), "CategoryId", "Text"));
}

Linq Is not working fine not getting any data in Ajax My Linq Query attached

I have two Tables one is "Questions" and second is "SurveyQuestion"
Questions has four column ID , Text, QuestionType, Options
and
SurveyQuestion has four column ID, SuerveyID , QuestionID, OrderID
I have Survey ID now trying to use LINQ and get all value from Question Table,
My Method calling from Ajax is in Controller that is,
public ActionResult Index(string prefix)
{
List<SelectList> Questions = new List<SelectList>();
// Here "MyDatabaseEntities " is dbContext, which is created at time of model creation.
SurveyAppEntities ObjectSur = new SurveyAppEntities();
// Questions = ObjectSur.Surveys.Where(a => a.ID.Equals(prefix)).toToList();
var e = from q in ObjectSur.Questions
join b in ObjectSur.SurveyQuestions on q.ID equals b.QuestionID
where b.SurveyID.Equals(prefix)
select q;
return Json(e, JsonRequestBehavior.AllowGet);
}
Ajax Cal and this method returning data process is working fine because i tried just to pass string and after changing that string i am getting in ajax alert but when use this linq not sending any result
Hopes for your suggestions
Ajax Call:
function MyFunction() {
alert($('#DDlSurvey').val());
$.ajax({
url: "#Url.Action("Index", "ConductSurvey")",
data: { prefix: $('#DDlSurvey').val() },
type: "POST",
dataType: "json",
success: function (data) {
// loadData(data);
alert(data)
alert("Success");
},
error: function () {
alert("Failed! Please try again.");
}
});
//$('#YourLabelId').val('ReplaceWithThisValue');
}
I hope this will help you.
var e = (from q in ObjectSur.Questions
join b in ObjectSur.SurveyQuestions on q.ID equals b.QuestionID
where b.SurveyID.Equals(prefix)
select q).ToList()

Fill Select2 dropdown box from database in MVC 4

I need help writing the jquery/ajax to fill a Select2 dropdown box.
For those who don't know what Select2 is, it is a javascript extension to provide Twitter Bootstrap looks and search / type-ahead functionality to an html select list dropdown box. For more information look at the examples here: Select2 Github page
UPDATED - Solved!
So I finally put this all together, and the solution to my problems was that I was missing functions to format the results and the list selection. The code below produces a functioning Select2 dropbox with type-ahead perfectly.
Json Method on Controller:
public JsonResult FetchItems(string query)
{
DatabaseContext dbContext = new DatabaseContext(); //init dbContext
List<Item> itemsList = dbContext.Items.ToList(); //fetch list of items from db table
List<Item> resultsList = new List<Item>; //create empty results list
foreach(var item in itemsList)
{
//if any item contains the query string
if (item.ItemName.IndexOf(query, StringComparison.OrdinalIgnoreCase) >= 0)
{
resultsList.Add(item); //then add item to the results list
}
}
resultsList.Sort(delegate(Item c1, Item c2) { return c1.ItemName.CompareTo(c2.ItemName); }); //sort the results list alphabetically by ItemName
var serialisedJson = from result in resultsList //serialise the results list into json
select new
{
name = result.ItemName, //each json object will have
id = result.ItemID //these two variables [name, id]
};
return Json(serialisedJson , JsonRequestBehavior.AllowGet); //return the serialised results list
}
The Json controller method above returns a list of serialised Json objects, whose ItemName contains the string 'query' provided (this 'query' comes from the search box in the Select2 drop box).
The code below is the Javascript in the view(or layout if you prefer) to power the Select2 drop box.
Javascript:
$("#hiddenHtmlInput").select2({
initSelection: function (element, callback) {
var elementText = "#ViewBag.currentItemName";
callback({ "name": elementText });
},
placeholder: "Select an Item",
allowClear: true,
style: "display: inline-block",
minimumInputLength: 2, //you can specify a min. query length to return results
ajax:{
cache: false,
dataType: "json",
type: "GET",
url: "#Url.Action("JsonControllerMethod", "ControllerName")",
data: function (searchTerm) {
return { query: searchTerm };
},
results: function (data) {
return {results: data};
}
},
formatResult: itemFormatResult,
formatSelection: function(item){
return item.name;
}
escapeMarkup: function (m) { return m; }
});
Then in the body of the view you need a hidden Input element, which Select2 will render the dropbox to.
Html:
<input id="hiddenHtmlInput" type="hidden" class="bigdrop" style="width: 30%" value=""/>
Or attach a MVC Razor html.hidden element to your view model to enable you to post the picked item Id back to the server.
Html (MVC Razor):
#Html.HiddenFor(m => m.ItemModel.ItemId, new { id = "hiddenHtmlInput", #class = "bigdrop", style = "width: 30%", placeholder = "Select an Item" })
Solved! Finally.
The full jquery is below, what was needed were two functions to format the returned results from the controller. This is because the dropbox needs some html markup to be wrapped around the results in order to be able to display them.
Also contractID was needed as an attribute in the controller as without it results were shown in the dropdown, but they could not be selected.
$("#contractName").select2({
placeholder: "Type to find a Contract",
allowClear: true,
minimumInputLength: 2,
ajax: {
cache: false,
dataType: "json",
type: "GET",
url: "#Url.Action("FetchContracts", "Leads")",
data: function(searchTerm){
return { query: searchTerm };
},
results: function(data){
return { results: data };
}
},
formatResult: contractFormatResult,
formatSelection: contractFormatSelection,
escapeMarkup: function (m) { return m; }
});
function contractFormatResult(contract) {
var markup = "<table class='contract-result'><tr>";
if (contract.name !== undefined) {
markup += "<div class='contract-name'>" + contract.name + "</div>";
}
markup += "</td></tr></table>"
return markup;
}
function contractFormatSelection(contract) {
return contract.name;
}
The problem is that you are returning a List<Contract> from that controller method, but the MVC runtime doesn't know how to hand that off to the browser. You need to return a JsonResult instead:
public JsonResult FetchContracts()
{
TelemarketingContext teleContext = new TelemarketingContext();
var contracts = teleContext.Contracts.ToList();
var json = from contract in contracts
select new {
name = contract.ContractName,
id = contract.ContactID,
};
return Json(json, JsonRequestBehavior.AllowGet);
}
Now, the data param of the AJAX : Success function will be the JSON from the controller. I'm not familiar with how this plugin works, but you should be able to loop through the json in data manually if you need to.
Select 2 seems to be a standard select with jquery attached so this should work:
Model:
public class vmDropDown
{
public IEnumerable<SelectListItem> DeviceList { get; set; }
[Required(ErrorMessage = "Please select at least one item")]
public IEnumerable<int> SelectedItems { get; set; }
}
Controller:
[HttpGet]
public ActionResult Assign(int id)
{
return View(CreateUnassignedModel(id));
}
[HttpPost]
public ActionResult Assign(vmDeviceAssign model)
{
if (ModelState.IsValid)
{
_deviceLogic.Assign(model.GroupId, model.SelectedItems);
return View("ConfirmDevice");
}
else // Validation error, so redisplay data entry form
{
return View(CreateUnassignedModel(model.GroupId));
}
}
private vmDeviceAssign CreateUnassignedModel(int id)
{
return new vmDeviceAssign
{
DeviceList = _deviceLogic.GetUnassigned(),
SelectedItems = null
};
}
View:
<div class="editor-field">
#Html.ListBoxFor(model => model.SelectedItems, new SelectList(Model.DeviceList, "Value", "Text"))
#Html.ValidationMessageFor(model => model.SelectedItems)
</div>
Cant give explanation as am at work but if you leave a message ill pick it up tonight

ASP.NET MVC Sort Listing by Selected item in DropDownList

I have a List of Listings within my Database. On my View, I have a DropDownList which contains categories. A category contains many listings.
When I select a specific category, I wish to only display those listings which have the category selected.
My main worry is how to generate the JQuery to call my SortListing method in my ListingController.
Here is the current HTML (Razor):
#Html.DropDownListFor(m => m.Categories, Model.Categories, "Select a Category")
My SortListing Method:
public List<Listing> SortListing(string categoryId)
{
var listings = new List<Listing>();
foreach (var listing in _service.ListAllEntities<Listing>())
{
if (listing.CategoryId == categoryId)
{
listings.Add(listing);
}
}
return listings;
}
EDIT I have the following. Put the categoryGuid is coming in null.
This is my code:
$(function () {
$('#SelectedCategoryGuid').change(function () {
var url = $(this).data('url');
var categoryId = $(this).val();
$.ajax({
url: url,
type: 'GET',
cache: false,
data: { categoryId: categoryId },
success: function (result) {
// TODO: manipulate the result returned from the controller action
}
});
});
});
</script>
<h2>Index</h2>
#Html.ActionLink("Create New Listing", "Create")
<br/>
<strong>Filter Listings</strong>
#Html.DropDownListFor(
m => m.SelectedCategoryGuid,
Model.Categories,
"Select a Category",
new {
id = "SelectedCategoryGuid",
data_url = Url.Action("SortListing", "Listing")
}
)
My main worry is how to generate the JQuery to call my SortListing
method in my ListingController.
Actually you should be having other worries as well that I will try to cover throughout my answer.
There's an issue with your DropDownListFor helper. You have used the same property on your model for both binding the selected category value and the list of categories which is wrong. The first parameter of the DropDownListFor helper represents a lambda expression pointing to a primitive type property on your view model:
#Html.DropDownListFor(
m => m.CategoryId,
Model.Categories,
"Select a Category",
new {
id = "categoryDdl",
data_url = Url.Action("SortListing", "Listing")
}
)
and then subscribe to the .change() event and trigger the AJAX request:
$(function() {
$('#categoryDdl').change(function() {
var url = $(this).data('url');
var categoryId = $(this).val();
$.ajax({
url: url,
type: 'GET',
cache: false,
data: { categoryId: categoryId },
success: function(result) {
// TODO: manipulate the result returned from the controller action
}
});
});
});
Now let's take a look at your SortListing controller action because there are issues with it. In ASP.NET MVC standard convention dictates that controller actions must return ActionResults. In your case you seem to be returning some List<Listing>. So the first thing you have to decide is the format you would like to use. One possibility is to return those listings as JSON formatted values:
public ActionResult SortListing(string categoryId)
{
var listings = _service
.ListAllEntities<Listing>()
.Where(x => x.CategoryId == categoryId)
.ToList();
return Json(listings, JsonRequestBehavior.AllowGet);
}
In this case inside your AJAX success callback you will receive this collection of listings and you will have to update your DOM:
success: function(result) {
// result represents an array of listings
// so you could loop through them and generate some DOM elements
}
Another possibility is to have your controller action return a partial view:
public ActionResult SortListing(string categoryId)
{
var listings = _service
.ListAllEntities<Listing>()
.Where(x => x.CategoryId == categoryId)
.ToList();
return PartialView("Listings", listings);
}
and then you will have a corresponding partial view:
#model List<Listing>
#foreach (var listing in Model)
{
<div>#listing.SomeProperty</div>
}
and then inside the success callback you will refresh some containing placeholder:
success: function(result) {
$('#SomeDivIdThatWrapsAroundTheListingsPartial').html(result);
}
So to recap you could either have the controller action return JSON and then manually build the corresponding DOM tree using javascript or return a partial view which will already contain the corresponding markup and simply refresh some containing div with this partial.

Ajax function to fetch the selected value from the dropdown and passing that value to a function in Controller

i am making an application in MVC3 where in i have many dropdowns
Now on the basis of value selected in the first dropdown the second drodown is populated.
I need to write Ajax for this and i am having a tough time doing it.
I Have my first dropdown "Select Course" and now which ever course is selected With the help of that particular Course Id the corresponding state is selected from the database.
For eg if the Course is "MCA" the states Dropdown must be populated with states such as Maharashtra,Rajasthan and soon.
I tried the Following code for Ajax but it does not work and gives me an error
$("#Course").change(function () {
var Courseid = $("#Course").val();
var urlCourselocation = '#Url.Action("FetchstatebyCourse")';
$.ajax({
type: "POST",
url: urlCourselocation,
data: { id: Courseid },
success: function (data) {
$('#State').empty();
$('#State')
.append($('<option>', { value: "0" })
.text("-- Select State --"));
$.each(returndata, function (key, value) {
$('#State')
.append($('<option>', { value: value.Value })
.text(value.Text));
});
}
});
});
and in the Controller i have wrote the following function:
public ActionResult FetchHobbyDetailByHobbyId(int Id)
{
LearnerService learnerservice = new LearnerService();
/* Here is some Code to fetch the state id from the database*/
ICollection<ProvincialState> state = learnerservice.FetchStateByStateid(stateid);
ViewBag.State = state;
if (HttpContext.Request.IsAjaxRequest())
return Json(new SelectList(
state,
"ProvincialStateID",
"ProvincialStateName"));
return View();
}
Please help me with the Code and correct me if i am wrong..
Oh I think I saw the issue...
shouldn't :
$.each(returndata, function (key, value) {
be
$.each(data, function (key, value) {

Resources