I have two dropdownlist. The selected value from the first one loads the other. How do I do that when I have the helper methods in a controller?
#using (Html.BeginForm())
{
<div>
<table width="100%" cellpadding="0" cellspacing="0">
<tr>
<td><b>Select a District:</b></td>
<td>#Html.DropDownListFor(m => m.DistrictId, ViewData["DMManagers"] as IEnumerable<SelectListItem>, "Select One")</td>
</tr>
<tr>
<td><b>Select a TM:</b></td>
<td>#Html.DropDownListFor(m => m.TMId, ViewData["TMManagers"] as IEnumerable<SelectListItem>, "Select One")</td>
</tr>
</table>
</div>
}
private void LoadDistrictManagers()
{
var _DMS = (from c in SessionHandler.CurrentContext.ChannelGroups
join cgt in SessionHandler.CurrentContext.ChannelGroupTypes on c.ChannelGroupTypeId equals cgt.ChannelGroupTypeId
where cgt.Name == "District Manager"
select new { c.ChannelGroupId, c.Name }).OrderBy(m => m.Name);
ViewData["DMManagers"] = new SelectList(_DMS, "ChannelGroupId", "Name");
}
private void LoadTerritoryManagers(int districtId)
{
var _TMS = (from c in SessionHandler.CurrentContext.ChannelGroups
join cgt in SessionHandler.CurrentContext.ChannelGroupTypes on c.ChannelGroupTypeId equals cgt.ChannelGroupTypeId
where cgt.Name == "Territory" && c.ParentChannelGroupId == districtId
select new { c.ChannelGroupId, c.Name }).OrderBy(m => m.Name);
ViewData["TMManagers"] = new SelectList(_TMS, "ChannelGroupId", "Name");
}
public ActionResult SummaryReport()
{
DistrictManagerModel model = new DistrictManagerModel();
LoadDistrictManagers();
return View("AreaManager", model);
}
Give both dropdowns unique IDs using the HTTPAttributes field:
#Html.DropDownListFor(m => m.DistrictId, ViewData["DMManagers"] as IEnumerable<SelectListItem>, "Select One", new {#id="ddlDMManagers"})
2nd dropdown should be initialized as an empty list:
#Html.DropDownListFor(m => m.TMId, Enumerable.Empty<SelectListItem>(), new {#id="ddlTMManagers"})
If you don't mind using jQuery ajax to update the 2nd dropdown when a 'change' event is triggered on the 1st dropdown:
$(function() {
$('select#ddlDMManagers').change(function() {
var districtId = $(this).val();
$.ajax({
url: 'LoadTerritoryManagers',
type: 'POST',
data: JSON.stringify({ districtId: districtId }),
dataType: 'json',
contentType: 'application/json',
success: function (data) {
$.each(data, function (key, TMManagers) {
$('select#ddlTMManagers').append('<option value="0">Select One</option>');
// loop through the TM Managers and fill the dropdown
$.each(TMManagers, function(index, manager) {
$('select#ddlTMManagers').append(
'<option value="' + manager.Id + '">'
+ manager.Name +
'</option>');
});
});
}
});
});
});
Add this class to your controller namespace:
public class TMManager
{
public int Id {get; set;}
public string Name {get; set;}
}
You will need to update your controller action, LoadTerritoryManagers(), to respond to the ajax request and return a JSON array of {Id,Name} objects.
[HttpPost]
public ActionResult LoadTerritoryManagers(int districtId)
{
var _TMS = (from c in SessionHandler.CurrentContext.ChannelGroups
join cgt in SessionHandler.CurrentContext.ChannelGroupTypes on c.ChannelGroupTypeId equals cgt.ChannelGroupTypeId
where cgt.Name == "Territory" && c.ParentChannelGroupId == districtId
select new TMManager(){ Id = c.ChannelGroupId, Name = c.Name }).OrderBy(m => m.Name);
if (_TMS == null)
return Json(null);
List<TMManager> managers = (List<TMManager>)_TMS.ToList();
return Json(managers);
}
Use the following code. It is used in my project. For Zone and Region I used two drop-down list. On change Zone data I loaded the Region drop-down.
In View page
#Html.DropDownList("ddlZone", new SelectList(#ViewBag.Zone, "Zone_Code", "Zone_Name"), "--Select--", new { #class = "LoginDropDown" })
#Html.DropDownList("ddlRegion", Enumerable.Empty<SelectListItem>(), new { #class = "LoginDropDown" })
The Zone need to load when the view page is load.
In the controller write this method for Region Load
[WebMethod]
public JsonResult LoadRegion(string zoneCode)
{
ArrayList arl = new ArrayList();
RASolarERPData objDal = new RASolarERPData();
List<tbl_Region> region = new List<tbl_Region>();
region = erpDal.RegionByZoneCode(zoneCode);
foreach (tbl_Region rg in region)
{
arl.Add(new { Value = rg.Reg_Code.ToString(), Display = rg.Reg_Name });
}
return new JsonResult { Data = arl };
}
Then use the following JavaScript
<script type="text/javascript">
$(document).ready(function () {
$('#ddlZone').change(function () {
LoadRegion(this.value);
});
function LoadRegion(zoneCode) {
$.ajax({
type: "POST",
url: '#Url.Action("LoadRegion", "RSFSecurity")',
data: "{'zoneCode':'" + zoneCode + "'}",
contentType: "application/json; charset=utf-8",
dataType: 'json',
cache: false,
success: function (data) {
$('#ddlRegion').get(0).options.length = 0;
$('#ddlRegion').get(0).options[0] = new Option("--Select--", "0");
$.map(data, function (item) {
$('#ddlRegion').get(0).options[$('#ddlRegion').get(0).options.length] = new Option(item.Display, item.Value);
});
},
error: function () {
alert("Failed to load Item");
}
});
}
});
</script>
We can use the jquery to get and fill the dropdown like this:
<script>
function FillCity() {
var stateId = $('#State').val();
$.ajax({
url: '/Employees/FillCity',
type: "GET",
dataType: "JSON",
data: { State: stateId},
success: function (cities) {
$("#City").html(""); // clear before appending new list
$.each(cities, function (i, city) {
$("#City").append(
$('<option></option>').val(city.CityId).html(city.CityName));
});
}
});
}
</script>
For more detail see
MVC DropDownListFor fill on selection change of another dropdown
Related
I have this code in cshtml file
#using (Html.BeginForm("UserPermission", "UserPermision", new { area = "Admin", id = "cbbDpm", name = "cbbDpm" }, FormMethod.Post))
{
#Html.DropDownListFor(m => m.Dept, new SelectList(Model.Dept, "DepartmentName", "DepartmentName"), "-- Select Department --", new { #class = "form-control w-100", #id = "cbbDpmt", #name = "cbbDpmt" })
}
...
<div id="partialDiv">
#Html.Partial("_Table")
</div>
...
<script>
$(document).ready(function () {
$("#cbbDpmt").on("change", function () {
$.ajax(
{
url: '/Admin/UserPermision/CBBSelectedChange?dpmname' + $(this).val(),
type: 'GET',
data: "",
contentType: 'application/json; charset=utf-8',
success: function (data) {
$("#partialDiv").html(data);
},
error: function () {
alert("error");
}
});
});
});
</script>
And in controller, I have:
[HttpGet]
public PartialViewResult CBBSelectedChange(string dpmname)
{
List<AdminUserPermission> userModels = DatabaseServer.ConvertDataTable<AdminUserPermission>(DatabaseServer.Read_Table(#"SELECT *
FROM dbo.tblWFX_UserGroup AS gr
JOIN dbo.tblWFX_Department AS dpm ON gr.DepartmentName = dpm.DepartmentID
WHERE dpm.DepartmentName = " + dpmname, false));
Session["selectedDept"] = dpmname;
AdminUserPermissionParty adminUserPermissionParties = new AdminUserPermissionParty();
adminUserPermissionParties.UserPermisionModel = userModels;
return PartialView("_Table", adminUserPermissionParties);
}
I want put selected item from combobox in cshtml into function in controller. I try to research many time but I can't put selected value from cbb into string dpmname.
Please help me.
You need to use [FromUri]
[HttpGet]
public PartialViewResult CBBSelectedChange([FromUri] string dpmname)
And also change Ajax call as follows:
$.ajax(
{
url: '/Admin/UserPermision/CBBSelectedChange?dpmname=' + $(this).val(),
type: 'GET',
contentType: 'application/json; charset=utf-8',
success: function (data) {
$("#partialDiv").html(data);
},
error: function () {
alert("error");
}
});
See: https://learn.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api
I have a dropdownlist contains a list of products which binds from database. I want to load selected product Data.
here is my code in view
#Html.DropDownListFor(model => model.ProductName, new SelectList(Model.ProductsList, "ProductID", "ProductName"), new
{
id = "Productslist",
#class = "GreenDropDownListStyle",
#datastyle = "dropdown",
#onchange = "FillProduct()"
})
I had use java Script code to send select Product Id then get it's data
<script type="text/javascript">
$(document).ready(function () {
$("#Productslist").change(function () {
debugger;
var selectedIndex = $(this).val();
var divH = document.getElementById(selectedIndex);
if (selectedIndex > 0) {
$.ajax(
{
url: '/Inventory/ViewProduct',
type: 'GET',
data: { ProductID: selectedIndex },
contentType: 'application/json; charset=utf-8',
success: function (data) {
///
},
error: function () {
alert("error");
}
});
}
else {
divH.style.visibility = 'hidden'; // Hide
}
});
});
</script>
the issue that this code send the selected index not the is for the selected product also its send the id as a string so it never go to my condition
last thing in case of succeed what i should write
it solved by
var ProductID = this.value;
I am using the following to generate a dropdownlist of provinces based on the country selection:
<select id="Province" name="Province" class="form-control input-sm">
#{
string[] provinces = ViewBag.ProvincesForSelectedCountry;
string selectedProvinceName = null;
}
#{
if (Model != null && !String.IsNullOrEmpty(Model.Province))
{
selectedProvinceName = Model.Province;
}
else
{
selectedProvinceName = ConfigData.DefaultProvinceName;
}
}
#foreach (var anEntry in provinces)
{
string selectedTextMark = anEntry == selectedProvinceName
? "selected=\"selected\""
: String.Empty;
<option value="#(anEntry)" #(selectedTextMark)>#(anEntry)</option>
}
</select>
The challenge is I don't have a list of provinces (states) for other countries! Is there a way to allow for the user to type in the name of the province? Like a combobox.
I had to do it using Knockout-Kendo combobox, here is the solution:
Controller:
public ActionResult Index()
{
ViewBag.CountryID = new SelectList(db.Countries, "ID", "Name", "34");
.....
public JsonResult GetState(int? id)
{
if (id == null)
{ id = 34; }
var data = db.States.Where(x => x.CountryID == id)
.Select( x =>
new
{
ID = x.ID,
Name = x.Name
}).ToList();
return Json(data, JsonRequestBehavior.AllowGet);
}
In the View:
#Html.DropDownList("Country", ViewBag.CountryID as SelectList, "Select...",
new { onchange = "UpdateProvinces();" })
<input data-bind="kendoComboBox: { dataTextField: 'Name', dataValueField: 'ID',
data: choices, value: selectedChoice }" />
Here is the JavaScript:
function UpdateProvinces() {
var countryId = $("#Country option:selected").val();
$.getJSON("/Home/GetState/" + countryId,
null,
function (data) {
objVM.choices(data);
});
}
function ItemViewModel(arg) {
arg = 34;
var self = this;
this.choices = ko.observableArray([]),
$.ajax({
type: "GET",
url: '#Url.Action("GetState", "Home")',
contentType: "application/json; charset=utf-8",
data: { id: arg },
dataType: "json",
success: function (data) {
self.choices(data);
},
error: function (err) {
alert(err.status + " : " + err.statusText);
}
});
var selectedChoice = {
ID: self.ID,
Name: self.Name
};
self.selectedChoice = ko.observable();
}
var objVM = new ItemViewModel();
ko.applyBindings(objVM);
Edit:
Another alternative is to use Telerik MVC UI Combobox http://demos.telerik.com/aspnet-mvc/combobox/cascadingcombobox
Below is my code, I am not sure what i am doing wrong?
Ajax json jquery code
function FillCity() {
var countryid = $("select[name$='.countryid']").val(); //<---- this is dynamic
$.ajax({
url: "Controller/FillMyCity",
type: "POST",
dataType: "json",
data: { country: countryid } ,
success: function (city) {
$("select[name$='.cityid']").html(""); // <--- this is dynamic
$.each(city, function (i, pp) {
$("select[name$='.cityid']").append(
$('<option></option>').val(pp.cityid).html(pp.name));
});
},
error: function (err) {
alert(err);
}
});
}
Controller method
public JsonResult FillMyCity(int country)
{
var cities = db.Cities.Where(x => x.countryid == country).ToList().Select(item => new City
{
cityid = item.cityid,
name = item.name
}).AsQueryable();
return Json(cities, JsonRequestBehavior.AllowGet);
}
View
#Html.DropDownList("Country[" + i + "].countryid", (SelectList)ViewData[countries], string.Empty, new { #class = "form-control countries", #id = "mycountry" + i + "", #onchange = "FillCity()" })
#Html.DropDownList("City[" + i + "].cityid", new SelectList(Enumerable.Empty<SelectListItem>(), "cityid", "name"), "Select city", new { #class = "form-control cities", #id = "mycity" + i + "" })
Output
EmployeeName Country City
Jenny ddl of countries ddl of cities
John ddl of countries ddl of cities
Problem 1: When I select country for Jenny, the cities ddl for both Jenny + John both get populated with Jenny's Country's cities, but it should only just applied for Jenny. When I select country for John the cities ddl list doesn't get populate So only Jenny's works, John doesn't
Problem 2: Since it is a dynamic json jquery appended html, I am unable to save the cities value, this is due to the fact that it is dynamic and doesn't appear in the view source.
Your use of $("select[name$='.countryid']").val(); will only ever select the value of the first element that has a name attribute ending with .countryid.
In addition, you use of DropDownList("Country[" + i + "].countryid", ...) is not the correct way to generate controls for a collection and its unlikely that will ever bind correctly to your model, however you have not shown the model so that cannot be fixed, so based on your current code, your view should be
<div class="container">
#Html.DropDownList("Country[" + i + "].countryid", (SelectList)ViewData[countries], string.Empty, new { #class = "form-control countries" })
#Html.DropDownList("City[" + i + "].cityid", Enumerable.Empty<SelectListItem>(), new { #class = "form-control cities" })
</div>
and the script
$('.countries').change(function() {
var country = $(this).val();
var cities = $(this).next('.cities'); // get the associated cities dropdownlist
cities.empty(); // clear existing options
$.ajax({
url: '#Url.Action("FillMyCity")', // do not hard code url's
type: "POST",
dataType: "json",
data: { country: country } ,
success: function (data) {
if (data) {
cities.append($('<option></option>').val('').text('Select city'));
$.each(data, function (index, item) {
cities.append($('<option</option>').val(item.cityid).html(item.name));
});
} else {
// oops
}
},
error: function (err) {
alert(err);
}
});
});
and finally, return a collection of anonymous objects containing only the data you need in the view to avoid sending extra data that will not be used
public JsonResult FillMyCity(int country)
{
// No need for .ToList()
var cities = db.Cities.Where(x => x.countryid == country).Select(item => new
{
cityid = item.cityid,
name = item.name
});
return Json(cities); // its a POST so no need for JsonRequestBehavior.AllowGet
}
I am trying to bind JSON Data to dropdown list
My Scenario is I want to get data and Bind to dynamic dropdown list,
In Seperate Class, I have used linq to get data like
public SelectList getProjects()
{
IEnumerable<SelectListItem> projectslist = (from proj in res.PROJECTs where proj.IS_DELETED == "N" select proj).AsEnumerable().Select(projt => new SelectListItem() { Text = projt.NAME, Value = projt.ID.ToString() });
return new SelectList(projectslist, "Value", "Text", PROJ_ID);
}
In Controller:
ViewBag.ProjectList=(from proj in res.PROJECTs where proj.IS_DELETED == "N" select proj).AsEnumerable().Select(projt => new SelectListItem() { Text = projt.NAME, Value = projt.ID.ToString() });
In View:
#for (int i = 0; i <2; i++)
{ {
#Html.DropDownListFor(m => m.GetTimeSheetDetails[i].PROJ_ID, (SelectList)ViewBag.ProjectList, "-- Choose a Project --", new { #class = "ddlProjectvalue" })
}
Now, I am trying for like if we have three dropdownlist, we select a list item in first dropdown list should not show in second dropdown list, and in third dropdown list should not show both previous selected list items for that i have writtern script like:
<script>
$(document).ready(function () {
$('.ddlProjectvalue').change(function () {
debugger;
var selectedValue = $(this).val();
if (selectedValue != null && selectedValue != '') {
debugger;
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "/Employer/GetDDLData?selectedValue="+selectedValue,
data: "{}",
dataType: "Json",
success: function (data) {
// first remove the current options if any
$('.ddlProjectvalue').find('option').remove();
// next iterate thru your object adding each option to the drop down\
$(data).each(function (index, item) { // GETTING ERROR HERE
debugger;
$('.ddlProjectvalue').append($('<option></option>').val(item.Value).html(item.Text));
});
},
error: function ajaxError(response) {
alert(response.status + ' ' + response.statusText);
}
});
}
});
});
</script>
and I am returning JSON Data from Controller:
public ActionResult GetDDLData(string selectedValue)
{
int projectid = Convert.ToInt32(selectedValue);
IEnumerable<SelectListItem> projectslist = (from proj in db.PROJECTs where proj.IS_DELETED == "N" && proj.ID != projectid select proj).AsEnumerable().Select(projt => new SelectListItem() { Text = projt.NAME, Value = projt.ID.ToString() });
var result = new SelectList(projectslist, "Value", "Text", tm.PROJ_ID);
return Json(result, JsonRequestBehavior.AllowGet);
}
I have tried, but getting Error like
"Syntax error, Unrecognized Expression"
where I am Doing Wrong , please help me anyone.
This will help you :
$.ajax({
url: "#Url.Action("GetDDLData","Employer")",
data: {selectedValue:selectedValue},
dataType: "json",
type: "GET",
error: function () {
alert(" An error occurred.");
},
success: function (data) {
var optionhtml1 = '<option value="' +
0 + '">' + "--Select State--" + '</option>';
$(".ddlProjectvalue").append(optionhtml1);
$.each(data, function (i) {
var optionhtml = '<option value="' +
data[i].Value + '">' +data[i].Text + '</option>';
$(".ddlProjectvalue").append(optionhtml);
});
}
});
//Controller Code
public ActionResult getAccount()
{
var result = new SelectList(db.Partymsts, "Account", "Account");
return Json(result, JsonRequestBehavior.AllowGet);
}
// js code
$.ajax({
type: "POST",
url: "/NewMaster/getAccount",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
var optionhtml1 = '<option value="' +
0 + '">' + "--Select State--" + '</option>';
$(".cs3").append(optionhtml1);
$.each(data, function (i) {
var optionhtml = '<option value="' +
data[i].Value + '">' +data[i].Text + '</option>';
$(".cs3").append(optionhtml);
});
}
});
// html code
<select id="cs3" name="cs3" class="cs3 form-control input-small"> </select>
its working !!
If your json is correct the below will work.Put the code in your ajax success
success:function(data){
$('.ddlProjectvalue').empty();
$.each(data,function (index, item) {
$('.ddlProjectvalue').append$('<option>', {
value: item.Value,
text: item.Text
}, '<option/>')
}
);
}
We have done in this way
Dropdown.append($('<option></option>').val(item.col1).text(item.col2));
function GetDropDownData(stateid) {
$.ajax({
type: 'GET',
url: '#Url.Action("getdist","Home")',
data: {stateid:stateid},
dataType: 'json',
success: function(data)
{
$("#districtId").empty();
$("#districtId").append('<option value="">--Select--</option>');
$.each(data, function (id, result) {
$("#districtId").append('<option value"'+result.Value+'">'+result.Text+'</option>');
});
},
failure: function () {
$("#districtId").empty();
$("#districtId").append('<option value="">--Select--</option>');
}
});
}