cascading dropdownlist with partial view issue - asp.net-mvc

I have a problem with cascading dropdownlists where the second ddl should appear in a partial view and I can't handle it by myself. Please help me to figure out why I have the following bag?
So, I have a view with the first ddl where the user can choose a brand:
#Html.DropDownList("brands", new SelectList(
#ViewBag.Brands, "Id", "BrandName"),
"--select a Brand--",
new
{
id = "ddlBrands",
data_url = Url.Action("ChooseModel", "Home")
})
<div id="divModel"></div>
The ChooseModel method returns the following partial view :
<div id="chooseModel">
<div class="lead">Model</div>
#Html.DropDownList("models", new SelectList(Enumerable.Empty<SelectListItem>
(), "Id", "ModelName"),
"--select a Model--",
new { id = "ddlModels" })
</div>
When a user selects an item in ddlBrands another dropdownlist for models should appear. So, the script looks like this:
$(function () {
$("#ddlBrands").change(function () {
var url = $(this).data('url');
var value = $(this).val();
$('#divModel').load(url, { id: value });
var brandId = $(this).val();
$('#divModel').html("");
$.getJSON("../Home/LoadModels", { brandId: brandId },
function (modelData) {
var select = $("#ddlModels");
select.empty();
select.append($('<option/>', {
value: 0,
text: "-- select a Model --"
}));
$.each(modelData, function (index, itemData) {
select.append($('<option/>', {
value: itemData.Value,
text: itemData.Text
}));
});
});
});
});
And, finally, LooksModels method loading the models for the particular brand:
public JsonResult LoadModels(string brandId)
{
if (string.IsNullOrEmpty(brandId))
return Json(HttpNotFound());
var modelList = unitOfWork.ModelRepository
.GetModelListByBrand(Convert.ToInt32(brandId)).ToList();
var modelData = modelList.Select(m => new SelectListItem()
{
Text = m.ModelName,
Value = m.Id.ToString()
});
return Json(modelData, JsonRequestBehavior.AllowGet);
}
So, when I launch the application and choose a brand in the first ddl, the child models showing fine in second one. Then I choose another brand, and again the right models appeared. But when I choose the brand that I chose first time, I can't choose any models - ddlModels shows me only --select a Model--.
Can you please tell me what error in script (I suppose) I have?

Try this Script :
<script type="text/javascript">
$(document).ready(function () {
$("#ddlBrands").change(function () {
firstDDLValue = $("#ddlBrands").val();
$.post('#Url.Action("LoadModels", "Home")', { fstValue: firstDDLValue }, function (result) {
var select = $("#ddlModels");
select.empty();
select.append($('<option/>', { value: '', text: '--Select--' }));
$.each(result, function (index, Data) {
select.append($('<option/>', {
value: Data.Value,
text: Data.Text
}));
});
});
});
});
</script>

Use This at Controller:
public JsonResult LoadModels(string fstValue)
{
YourClassname obj= new YourClassname ();
int Id = 0;
if (fstValue != "")
Id = Convert.ToInt32(fstValue);
var result = obj.GetModelListByBrand(Convert.ToInt32(Id ));
IList<SelectListItem> Data = new List<SelectListItem>();
for (int i = 0; i < result.Count; i++)
{
Data.Add(new SelectListItem()
{
Text = result[i].Text,
Value = result[i].Value,
});
}
return Json(Data, JsonRequestBehavior.AllowGet);
}

Related

How can I show related data in full calendar from multiple tables?

I have asp.net mvc site with full calendar. I also created tables like 'Event' and 'Room'. In my event table i have RoomId field.
This is how my function looks:
$(document).ready(function () {
var events = [];
var selectedEvent = null;
FetchEventAndRenderCalendar();
function FetchEventAndRenderCalendar() {
events = [];
$.ajax({
type: "GET",
url: "/CalendarEvent/GetEvents",
success: function (data) {
$.each(data, function (i, v) {
events.push({
eventID: v.Id,
title: v.Job,
description: v.Description,
start: moment(v.Start),
end: v.DutyEnd != null ? moment(v.End) : null,
room: v.RoomId,
});
})
GenerateCalender(events);
},
error: function (error) {
alert('failed');
}
})
}
On this moment, calendar displays Id. How can I refer to another table?
And this is my controller:
public JsonResult GetEvents()
{
using (Context dc = new Context())
{
dc.Configuration.LazyLoadingEnabled = false;
var events = dc.Event.ToList();
return new JsonResult { Data = events, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
You will need to join the event table with the room table. In your controller method GetEvents() you can create a select query something along the lines of the following:
var query = (from event in dc.event
join rooms in dc.rooms on event.roomId equals rooms.roomId
select new
{
eventID: event.Id,
title: event.Job,
description: event.Description,
roomId: room.RoomId,
roomName: room.Name
roomSize: room.Size
}).ToList();
Hope this helps.

How to refresh Html.DropDownGroupList after another dropdown changes

I have difficulties to refresh an Html.DropDownGroupList.
I have two dropdowns which depends on each other: Makes and Models. The Models dropdown should be grouped, as you can see in the attached screenshot.
When I enter in the page the Models dropdown is filled with data and it is grouped correctly, but when I change the first dropdown, the Model is not refreshing correctly.
In the controller I have this code:
public ActionResult GetModels(string id)
{
if (!string.IsNullOrEmpty(id))
{
int number;
bool result = Int32.TryParse(id, out number);
if (!result)
return Json(null);
var selectedMake = makeRepository.GetMakeByID(number);
var list1 = db.Models.Where(m => m.MakeID == selectedMake.ID).ToList();
List<GroupedSelectListItem> models = new List<GroupedSelectListItem>();
foreach (var items in list1)
{
models.Add(new GroupedSelectListItem
{
Text = items.Name,
Value = items.ID.ToString(),
GroupName = items.GroupName,
GroupKey = items.GroupName
});
}
ViewBag.Alma = models;
return Json(models, JsonRequestBehavior.AllowGet);
}
return Json(null);
}
and in the View :
#Html.DropDownGroupList("models", ViewBag.Alma as List<GroupedSelectListItem>, "Select Model", new
{
#class = "dropdown-toggle col-md-9 form-control"
})
This is the code where I try to refresh the dropdown:
$.ajax({
type: 'POST',
url: '#Url.Action("GetModels")',
dataType: 'json',
data: { id: $("#makes").val() },
success: function (models) {
if (window.console) {
console.log(JSON.stringify(models))
}
$.each(models, function (i, model) {
$("#models").append
('<optgroup label="'+ model.GroupName + '"><option value="' + model.Value + '">' +
model.Text + '</option></optgroup>'
);
});
}
});
This is the way the dropdown looks after the refresh
The grouping is not working anymore. I know that this is the problem:
$("#models").append('<optgroup label="'+ model.GroupName + '"><option value="' + model.Value + '">' + model.Text + '</option></optgroup>');
but how to do this ajax call to group my dropdown? I don't have so much experience with ajax, javascript.
Can you please advise how to refresh the Model dropdown?
Your GetModels() method is returning List<GroupedSelectListItem> which is a special class used by the DropDownGroupList() method and is not suitable for building your html (at least without a lot of extra code to group data in the script).
Start by creating view models to represent the hierarchical data you need
public class GroupVM
{
public string Name { get; set; }
public IEnumerable<OptionVM> Options { get; set; }
}
public class OptionVM
{
public int Value { get; set; }
public string Text { get; set; }
}
Then modify the controller to group your data and project the results to the view model
public ActionResult GetModels(int? id)
{
if (!id.HasValue)
{
return Json(null);
}
var data = db.Models.Where(x => x.MakeID == id.Value).GroupBy(x => x.GroupName).Select(x => new GroupVM()
{
Name = x.Key,
Options = x.Select(y => new OptionVM()
{
Value = y.ID,
Text= y.Name
})
});
return Json(data);
}
And modify your script to
var models = $('#models'); // cache it
$('#makes').change(function () {
var id = $(this).val();
$.ajax({
type: 'POST',
url: '#Url.Action("GetModels")',
dataType: 'json',
data: { id: id },
success: function (data) {
models.empty(); // clear existing options
$.each(data, function (index, group) {
var optGroup = $('<optgroup></optgroup>').attr('label', group.Name);
$.each(group.Options, function (index, option) {
var option = $('<option></option>').val(option.Value).text(option.Text);
optGroup.append(option);
});
models.append(optGroup);
});
}
});
})

how to set selected values to a multi select dropdown list on form load in .net mvc

I am using a multi select dropdown for a particular entry, which is retrieved from a table. If I am trying to edit this entry the selected dropdown is not showing.
This is my script.
<script type="text/javascript">
$(document).ready(function () {
//$('#Supplier').click(function () {
var sku = $("#SKU").val();
alert(sku);
//var pay = null;
//alert(suppid);
$.ajax({
url: '/SKUMasterSetup/supplierlist',
type: 'POST',
dataType: 'json',
data: { id: sku },
success: function (Supplierdata) {
alert("hi");
alert(Supplierdata);
var x = Supplierdata.length();
alert(x);
//<option value="{$T.data.Value}">{$T.data.Text}</option>
//for (var i = 0; i < Supplierdata.length; i++) {
// $("#supplier").append("Selected", Supplierdata[i], "selected").attr('selected', true);
for (var i in Supplierdata) {
var optionVal = Supplierdata[i];
$("#supplier").find("option[value=" + optionVal + "]").prop("selected", "selected");
}
// $('.class1').append("<option>" + "Please select" + "</option>");
},
//error : function (Supplier) { alert("Error !"); };
});
});
</script>
And my controller code is:
[HttpPost]
public JsonResult supplierlist(int id)
{
var Supplierdata = (from item in db.SupplierSKUMaps
where item.SKU == id
select item.SupplierMaster.SupplierName).ToList();
return Json(Supplierdata, JsonRequestBehavior.AllowGet);
}
And my dropdownlist is:
#Html.DropDownList("Supplier", ViewBag.Supplier as MultiSelectList, new { #class = "chosen", #id="supplier", #multiple = "multiple" })
you could always use #Value = #Html.Action(getMyFields) and within your controller, place an action method that returns Content result(MyData.ToList()).
More information on creating dropdowns can be found here: http://odetocode.com/blogs/scott/archive/2013/03/11/dropdownlistfor-with-asp-net-mvc.aspx

Cannot get value of HtmlAttributes item in kendo MVC treeview

I am using the Kendo MVC wrapper extensions to create a TreeView from my models. I would like to pass some data from the model with HtmlAttributes to the view.
Here is my Action :
public ActionResult Index()
{
var nodeList = new List<TreeViewItemModel>();
nodeList.Add(new TreeViewItemModel
{
Id = "1",
Text = "Item 1",
HasChildren = true,
HtmlAttributes = new Dictionary<string, string>
{
{"class","XXXX"}
},
Items = new List<TreeViewItemModel>
{
new TreeViewItemModel{Id="1.1", Text = "sub Item 1.1",HasChildren = false},
new TreeViewItemModel{Id="1.2", Text = "sub Item 1.2",HasChildren = false}
});
nodeList.Add(new TreeViewItemModel { Id = "2", Text = "Item 2", HasChildren = false });
return View(nodeList);
}
Here is my view :
#using Kendo.Mvc.UI
#model IEnumerable<Kendo.Mvc.UI.TreeViewItemModel>
#(Html.Kendo().TreeView()
.Name("treeView")
.BindTo(Model)
.DragAndDrop(true)
)
Here is the element from Chrome
<li class="k-item k-first" data-id="1" data-uid="6263f4c5-85f3-446c-a843-7d3786fb0f68" role="treeitem" id="treeView_tv_active">
As you can see there isn't any class:XXX in my li Tag So how can I give The XXX class to li Tag?
I can't figure out how to do this automatically, so here's a workaround.
C# passes back a List<Kendo.Mvc.UI.TreeViewItemModel>() to the treeview->datasource->transport->read event:
var items = new List<Kendo.Mvc.UI.TreeViewItemModel>();
////////////////////////////////////////////////////////////////////////////////
// areas of expertise
var aoe = new Kendo.Mvc.UI.TreeViewItemModel()
{
Text = "Areas of Expertise",
Id = "resume-treeview-category-AreasOfExpertise",
HasChildren = false,
HtmlAttributes = new Dictionary<string, string>(){{ "class", "resume-treeview-category"}, {"cat-id", "AreasOfExpertise" }},
};
items.Add(aoe);
return Json(items, JsonRequestBehavior.AllowGet);
I then hook the dataBound event to add the above attributes into the treeview item.
jQuery(document).ready(function ($) {
$("#document-treeview").kendoTreeView({
dataTextField: "Text",
dataSource: {
transport: {
read: {
type: 'POST',
url: "#Url.Action("GetAllTreeData", "Document2")",
contentType: 'application/json; charset=utf-8',
dataType: 'json'
},
parameterMap: function (data, type) {
if (type == "read") {
return JSON.stringify({
id: ResumeId
});
}
}
},
schema: {
model: {
id: "Id",
hasChildren: "HasChildren",
children: "Items"
}
}
},
dataBound: function(e) {
// Apparently reading an item after treeview creation doesn't apply the html attributes. Do that here.
var len = this.dataSource.data().length;
for (var i = 0; i < len; i++)
{
var dataItem = this.dataSource.data()[i];
var uid = dataItem.uid;
var li = $('#document-treeview li[data-uid="' + uid + '"]');
li.addClass(dataItem['HtmlAttributes']['class']);
li.attr('cat-id', dataItem['HtmlAttributes']['cat-id']);
}
}
});
}
Note the HtmlAttributes added from C# are explicitly handled in JavaScript =/

Populating dropdown with JSON result - Cascading DropDown using MVC3, JQuery, Ajax, JSON

I've got a cascading drop-drown using mvc. Something like, if you select a country in the first-dropdown, the states of that country in the second one should be populated accordingly.
At the moment, all seems fine and I'm getting Json response (saw it using F12 tools), and it looks something like [{ "stateId":"01", "StateName": "arizona" } , { "stateId" : "02", "StateName":"California" }, etc..] ..
I'd like to know how to populate my second-dropdown with this data. My second drop-down's id is "StateID". Any help would be greatly appreciated.
Below is the code used to produce the JSON Response from the server:
[HttpPost]
public JsonResult GetStates(string CountryID)
{
using (mdb)
{
var statesResults = from q in mdb.GetStates(CountryID)
select new Models.StatesDTO
{
StateID = q.StateID,
StateName = q.StateName
};
locations.statesList = stateResults.ToList();
}
JsonResult result = new JsonResult();
result.Data = locations.statesList;
return result;
}
Below is the client-side HTML, my razor-code and my script. I want to write some code inside "success:" so that it populates the States dropdown with the JSON data.
<script type="text/javascript">
$(function () {
$("select#CountryID").change(function (evt) {
if ($("select#CountryID").val() != "-1") {
$.ajax({
url: "/Home/GetStates",
type: 'POST',
data: { CountryID: $("select#CountryID").val() },
success: function () { alert("Data retrieval successful"); },
error: function (xhr) { alert("Something seems Wrong"); }
});
}
});
});
</script>
To begin with, inside a jQuery event handler function this refers to the element that triggered the event, so you can replace the additional calls to $("select#CountryID") with $(this). Though where possible you should access element properties directly, rather than using the jQuery functions, so you could simply do this.value rather than $(this).val() or $("select#CountryID").val().
Then, inside your AJAX calls success function, you need to create a series of <option> elements. That can be done using the base jQuery() function (or $() for short). That would look something like this:
$.ajax({
success: function(states) {
// states is your JSON array
var $select = $('#StateID');
$.each(states, function(i, state) {
$('<option>', {
value: state.stateId
}).html(state.StateName).appendTo($select);
});
}
});
Here's a jsFiddle demo.
Relevant jQuery docs:
jQuery.each()
jQuery()
In my project i am doing like this it's below
iN MY Controller
public JsonResult State(int countryId)
{
var stateList = CityRepository.GetList(countryId);
return Json(stateList, JsonRequestBehavior.AllowGet);
}
In Model
public IQueryable<Models.State> GetList(int CountryID)
{
var statelist = db.States.Where(x => x.CountryID == CountryID).ToList().Select(item => new State
{
ID = item.ID,
StateName = item.StateName
}).AsQueryable();
return statelist;
}
In view
<script type="text/javascript">
function cascadingdropdown() {
$("#stateID").empty();
$("#stateID").append("<option value='0'>--Select State--</option>");
var countryID = $('#countryID').val();
var Url="#Url.Content("~/City/State")";
$.ajax({
url:Url,
dataType: 'json',
data: { countryId: countryID },
success: function (data) {
$("#stateID").empty();
$("#stateID").append("<option value='0'>--Select State--</option>");
$.each(data, function (index, optiondata) {
$("#stateID").append("<option value='" + optiondata.ID + "'>" + optiondata.StateName + "</option>");
});
}
});
}
</script>
i think this will help you......
Step 1:
At very first, we need a model class that defines properties for storing data.
public class ApplicationForm
{
public string Name { get; set; }
public string State { get; set; }
public string District { get; set; }
}
Step 2:
Now, we need an initial controller that will return an Index view by packing list of states in ViewBag.StateName.
public ActionResult Index()
{
List<SelectListItem> state = new List<SelectListItem>();
state.Add(new SelectListItem { Text = "Bihar", Value = "Bihar" });
state.Add(new SelectListItem { Text = "Jharkhand", Value = "Jharkhand" });
ViewBag.StateName = new SelectList(state, "Value", "Text");
return View();
}
In above controller we have a List containing states attached to ViewBag.StateName. We could get list of states form database using Linq query or something and pack it to ViewBag.StateName, well let’s go with in-memory data.
Step 3:
Once we have controller we can add its view and start creating a Razor form.
#Html.ValidationSummary("Please correct the errors and try again.")
#using (Html.BeginForm())
{
<fieldset>
<legend>DropDownList</legend>
#Html.Label("Name")
#Html.TextBox("Name")
#Html.ValidationMessage("Name", "*")
#Html.Label("State")
#Html.DropDownList("State", ViewBag.StateName as SelectList, "Select a State", new { id = "State" })
#Html.ValidationMessage("State", "*")
#Html.Label("District")
<select id="District" name="District"></select>
#Html.ValidationMessage("District", "*")
<p>
<input type="submit" value="Create" id="SubmitId" />
</p>
</fieldset>
}
You can see I have added proper labels and validation fields with each input controls (two DropDownList and one TextBox) and also a validation summery at the top. Notice, I have used which is HTML instead of Razor helper this is because when we make JSON call using jQuery will return HTML markup of pre-populated option tag. Now, let’s add jQuery code in the above view page.
Step 4:
Here is the jQuery code making JSON call to DDL named controller’s DistrictList method with a parameter (which is selected state name). DistrictList method will returns JSON data. With the returned JSON data we are building tag HTML markup and attaching this HTML markup to ‘District’ which is DOM control.
#Scripts.Render("~/bundles/jquery")
<script type="text/jscript">
$(function () {
$('#State').change(function () {
$.getJSON('/DDL/DistrictList/' + $('#State').val(), function (data) {
var items = '<option>Select a District</option>';
$.each(data, function (i, district) {
items += "<option value='" + district.Value + "'>" + district.Text + "</option>";
});
$('#District').html(items);
});
});
});
</script>
Please make sure you are using jQuery library references before the tag.
Step 5:
In above jQuery code we are making a JSON call to DDL named controller’s DistrictList method with a parameter. Here is the DistrictList method code which will return JSON data.
public JsonResult DistrictList(string Id)
{
var district = from s in District.GetDistrict()
where s.StateName == Id
select s;
return Json(new SelectList(district.ToArray(), "StateName", "DistrictName"), JsonRequestBehavior.AllowGet);
}
Please note, DistrictList method will accept an ‘Id’ (it should be 'Id' always) parameter of string type sent by the jQuery JSON call. Inside the method, I am using ‘Id’ parameter in linq query to get list of matching districts and conceptually, in the list of district data there should be a state field. Also note, in the linq query I am making a method call District.GetDistrict().
Step 6:
In above District.GetDistrict() method call, District is a model which has a GetDistrict() method. And I am using GetDistrict() method in linq query, so this method should be of type IQueryable. Here is the model code.
public class District
{
public string StateName { get; set; }
public string DistrictName { get; set; }
public static IQueryable<District> GetDistrict()
{
return new List<District>
{
new District { StateName = "Bihar", DistrictName = "Motihari" },
new District { StateName = "Bihar", DistrictName = "Muzaffarpur" },
new District { StateName = "Bihar", DistrictName = "Patna" },
new District { StateName = "Jharkhand", DistrictName = "Bokaro" },
new District { StateName = "Jharkhand", DistrictName = "Ranchi" },
}.AsQueryable();
}
}
Step 7:
You can run the application here because cascading dropdownlist is ready now. I am going to do some validation works when user clicks the submit button. So, I will add another action result of POST version.
[HttpPost]
public ActionResult Index(ApplicationForm formdata)
{
if (formdata.Name == null)
{
ModelState.AddModelError("Name", "Name is required field.");
}
if (formdata.State == null)
{
ModelState.AddModelError("State", "State is required field.");
}
if (formdata.District == null)
{
ModelState.AddModelError("District", "District is required field.");
}
if (!ModelState.IsValid)
{
//Populate the list again
List<SelectListItem> state = new List<SelectListItem>();
state.Add(new SelectListItem { Text = "Bihar", Value = "Bihar" });
state.Add(new SelectListItem { Text = "Jharkhand", Value = "Jharkhand" });
ViewBag.StateName = new SelectList(state, "Value", "Text");
return View("Index");
}
//TODO: Database Insertion
return RedirectToAction("Index", "Home");
}
Try this inside the ajax call:
$.ajax({
url: "/Home/GetStates",
type: 'POST',
data: {
CountryID: $("select#CountryID").val()
},
success: function (data) {
alert("Data retrieval successful");
var items = "";
$.each(data, function (i, val) {
items += "<option value='" + val.stateId + "'>" + val.StateName + "</option>";
});
$("select#StateID").empty().html(items);
},
error: function (xhr) {
alert("Something seems Wrong");
}
});
EDIT 1
success: function (data) {
$.each(data, function (i, val) {
$('select#StateID').append(
$("<option></option>")
.attr("value", val.stateId)
.text(val.StateName));
});
},
I know this post is a year old but I found it and so might you. I use the following solution and it works very well. Strong typed without the need to write a single line of Javascript.
mvc4ajaxdropdownlist.codeplex.com
You can download it via Visual Studio as a NuGet package.
You should consider using some client-side view engine that binds a model (in your case JSON returned from API) to template (HTML code for SELECT). Angular and React might be to complex for this use case, but JQuery view engine enables you to easily load JSON model into template using MVC-like approach:
<script type="text/javascript">
$(function () {
$("select#CountryID").change(function (evt) {
if ($("select#CountryID").val() != "-1") {
$.ajax({
url: "/Home/GetStates",
type: 'POST',
data: { CountryID: $("select#CountryID").val() },
success: function (response) {
$("#stateID").empty();
$("#stateID").view(response);
},
error: function (xhr) { alert("Something seems Wrong"); }
});
}
});
});
</script>
It is much cleaner that generating raw HTML in JavaScript. See details here: https://jocapc.github.io/jquery-view-engine/docs/ajax-dropdown
Try this:
public JsonResult getdist(int stateid)
{
var res = objdal.getddl(7, stateid).Select(m => new SelectListItem { Text = m.Name, Value = m.Id.ToString() });
return Json(res,JsonRequestBehavior.AllowGet);
}
<script type="text/javascript">
$(document).ready(function () {
$("#ddlStateId").change(function () {
var url = '#Url.Content("~/")' + "Home/Cities_SelectedState";
var ddlsource = "#ddlStateId";
var ddltarget = "#ddlCityId";
$.getJSON(url, { Sel_StateName: $(ddlsource).val() }, function (data) {
$(ddltarget).empty();
$.each(data, function (index, optionData) {
$(ddltarget).append("<option value='" + optionData.Text + "'>" + optionData.Value + "</option>");
});
});
});
});
</script>

Resources