Cascading Drop Down List - ASP.NET MVC - c#

I work with ASP.NET MVC and I have an ODBC connection for database and have retrieved two drop down list from controller to view using queries.
Those two drop down lists are:
#Html.DropDownListFor(model => model.storageLocation, new SelectList(Model.locationGroupDD, "storageLocation", "storageLocation"), "Choose Location Group", new { #id = "storageLocation", #class = "dropdown1" })
#Html.DropDownListFor(model => model.storageLocationList, new SelectList(Model.locationDD,"storageLocationList","storageLocationList"), "Choose Location", new { #id = "storageLocationListDropDown", #class = "dropdown1" })
I'm new to JQuery and not sure how to script this. However, I found this script online and tried using the following to make necessary changes but I literally don't know how to modify/proceed. Any help is appreciated! Thank you.
Following are the queries I used to retrieve the data from database:
For drop downlist 1: select abc from xyz;
For drop downlist 2: select pqr from lmn where abc = "some value";
I want to pass the selected value from drop down list 1 to controller to execute query for second drop down list.

Please follow the following steps to make Cascading DropdownList in ASP.NET MVC:
1. In your Controller:
public class YourControlleNameController : Controller
{
public ActionResult Create()
{
var LocationGroupDDList = _dbContext.LocationGroupDD.Select(lgdd =>
new { lgdd.LocationGroupDDId, lgdd.LocationGroupDDName }).ToList();
ViewBag.LocationGroupDDSelectList = new SelectList(LocationGroupDDList, "LocationGroupDDId", "LocationGroupDDName");
ViewBag.LocationDDListSelectList = new SelectList(new List<LocationDD>(), "LocationDDId", "LocationDDName");
return View();
}
[HttpPost]
public ActionResult Create(YourModel model, string LocationGroupDDId)
{
if (ModelState.IsValid)
{
// Do necessary staff here
}
var LocationGroupDDList = _dbContext.LocationGroupDD.Select(lgdd =>
new { lgdd.LocationGroupDDId, lgdd.LocationGroupDDName }).ToList();
ViewBag.LocationGroupDDSelectList = new SelectList(LocationGroupDDList, "LocationGroupDDId", "LocationGroupDDName",LocationGroupDDId);
var LocationDDList = _dbContext.LocationDD.Where(ldd => ldd.LocationGroupDDId == LocationGroupDDId).Select(ldd => new {ldd.LocationDDId, ldd.LocationDDName}).ToList();
ViewBag.LocationDDListSelectList = new SelectList(LocationDDList, "LocationDDId", "LocationDDName",model.LocationDDId);
return View();
}
public JsonResult GetLocationDDByLocationGroupDD(string LocationGroupDDId)
{
var LocationDDList = _dbContext.LocationDD.Where(ldd => ldd.LocationGroupDDId == LocationGroupDDId)
.Select(ldd => new {ldd.LocationDDId, ldd.LocationDDName}).ToList();
return Json(LocationDDList, JsonRequestBehavior.AllowGet);
}
}
2. In the View:
<div class="form-group">
#Html.Label("LocationGroupDD", "Location GroupDD Name", htmlAttributes: new { #class = "control-label" })
#Html.DropDownList("LocationGroupDDId", ViewBag.LocationGroupDDSelectList as SelectList, "Select Location GroupDD", htmlAttributes: new { #class = "form-control", #id = "LocationGroupDD" })
</div>
<div class="form-group">
#Html.Label("LocationDD", "LocationDD Name", htmlAttributes: new { #class = "control-label" })
#Html.DropDownList("LocationDDId", ViewBag.LocationDDListSelectList as SelectList, "Select LocationDD", htmlAttributes: new { #class = "form-control", #disabled = "disabled", #id = "LocationDD" })
</div>
3. jQuery in the view:
#section Scripts {
<script type="text/javascript">
$(document).on('change','#LocationGroupDD', function(){
var LocationGroupDDId = $(this).val();
$('#LocationDD').empty();
if (LocationGroupDDId) {
$.ajax({
type: "GET",
url: '#Url.Action("GetLocationDDByLocationGroupDD", "YourControlleName")',
data: { LocationGroupDDId: LocationGroupDDId},
success: function(data) {
if (data.length > 0) {
$('#LocationDD').prop("disabled", false);
$('#LocationDD').append($("<option>").val("").text("Select LocationDD"));
$(data).each(function(index, item) {
$('#LocationDD').append($("<option>").val(item.LocationDDId).text(item.LocationDDName));
});
} else {
$('#LocationDD').append($("<option>").val("").text("LocationDD List Is Empty"));
}
}
});
} else {
$('#LocationDD').prop("disabled", true);
$('#LocationDD').append($("<option>").val("").text("Select Location GroupDD First"));
}
});
</script>
}
Hope this will solve your problem!

Related

Remove item from dropdownlist ASP.NET MVC 5 and C#

I do already have dropdownlist in my ASP.NET MVC 5 project.
I need to remove one of the item parameter call it "Admin"; I want remove it from the list when the page is loaded.
This is my Razor markup:
<div class="form-group">
#Html.LabelFor(model => model.RoleName, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-9">
#Html.DropDownListFor(model => model.RoleName, Model.VMRoles, new { #class = "form
control input-sm", multiple= "multiple" })
#Html.ValidationMessageFor(model => model.RoleName, "", new { #class = "text-danger" })
</div>
</div>
And this the C# controller:
[HttpGet]
[Authorize]
public ActionResult Create()
{
var vm = new CreateUserViewModel
{
VMSisterConcerns = _sisterConcernService.GetAllSisterConcern().Select(c => new SelectListItem { Text = c.Name, Value = c.ConcernID.ToString() }).ToList(),
VMRoles = _roleService.GetAllRole().Select(r => new SelectListItem { Text = r.Name, Value = r.Name }).ToList(),
ConcernId = User.Identity.GetConcernId().ToString()
};
return View(vm);
}
And this the model:
public ICollection<System.Web.Mvc.SelectListItem> VMRoles { get; set; }
Here is the correct answer thanks for #itsme86 he mention How to understand LINQ .
VMRoles = _roleService.GetAllRole().Where(r => r.name != "Admin").Select(r => new SelectListItem { Text = r.Name, Value = r.Name }).ToList(),

Dependent dropdownlist in ASP.NET MVC

At present I have two tables (Teams and Employees)
I am populating the dropdownList for Teams perfectly, next I am trying to populate the second dropdownlist depending on the selectedId of Teams for Employees.
Controller:
// GET: CalView
public ActionResult Index(string ses, string DH)
{ //Team Lead Members
var eID = Convert.ToInt32(Session["currentEmployeeID"]);
var EmpID = Session["currentEmpID"];
Employee obj = (from o in db.Employees
where o.EnrollNumber == EmpID
select o).FirstOrDefault();
Department dept = (from dep in db.Departments
where dep.LeadBy == obj.EmployeeId
select dep).FirstOrDefault();
//this works fine
ViewBag.showTeams = new SelectList(db.Teams.Where(tm => (tm.DeptID == dept.DepartmentId) && (dept.LeadBy == eID)), "TeamID","Name");
//this obviously does not
ViewBag.showMembers = new SelectList(db.Employees.Where(empt => (empT.TeamID == selectedIdFromPreviousDropDownList), "EmployeeID", "Employee"));
return View();
}
View:
if ((Session["UT"] == "DD") && (#ViewBag.DeptLead != null))
{
//this works
#Html.DropDownList("showTeams", null, "-Select Team-", htmlAttributes: new { #class = "form-control" })
//this does not work
#Html.DropDownList("showMembers", null, "-Select Team-", htmlAttributes: new { #class = "form-control" })
}
Do I need some AJAX call? or perhaps a POST method? Totally new to MVC.
Do I need some AJAX call? or perhaps a POST method? Okay then, lets do it this way:
Give your DropdownLists some id's probably:
#Html.DropDownList("showTeams", null, "-Select Team-", htmlAttributes: new { id = "ddshowTeams", #class = "form-control" })
#Html.DropDownList("showMembers", null, "-Select Team-", htmlAttributes: new {id = "ddshowMembers", #class = "form-control" })
Create a jsonResult function, GetMembers and some Magic right there:
<script type="text/javascript">
$(document).ready(function () {
//Dropdownlist Selectedchange event
$("#ddshowTeams").change(function () {
console.log("pehla andar");
$("#ddshowMembers").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("GetMembers")',
dataType: 'json',
data: { id: $("#ddshowTeams").val() },
success: function (mems) {
console.log("wich ayaeee");
// states contains the JSON formatted list
// of states passed from the controller
$.each(mems, function (i, member) {
$("#ddshowMembers").append('<option value="'
+ member.Value + '">'
+ member.Text + '</option>');
});
},
error: function (ex) {
alert('Failed to retrieve states.' + ex);
}
});
return false;
})
});
</script>
and in your controller:
public JsonResult GetMembers(int id)
{
return Json(new SelectList(db.Employees.Where(empt => (empt.TeamId == id)), "EmployeeID", "FirstName"));
}

MVC Edit form with dynamic dropdown list - How to set initial values [duplicate]

This question already has an answer here:
How to keep cascade dropdownlist selected items after form submit?
(1 answer)
Closed 5 years ago.
I'm using MVC , C# and Entity Framework.
The object on my model are:
State-------- Id , Name
City ------- Id , Name , StateId
TheObject----Id, Name, StateId, CityId
I want to create an edit form for TheObject.
The Edit form has 2 dropdownlist State and City that are created dynamically , and the City list depend on selection made on State List.
The problem is that the dropdown list are filled correctly , but when the edit form is open these 2 dropdownlist are in empty state and does not have selected the real values for the object that is edited .
The partial code for Edit view is this :
<div class="form-group">
#Html.LabelFor(u => u.State, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(u => u.State,
new SelectList(ViewBag.State, "Id", "Name"),
"Choose State",
new { #class = "form-control", #onchange = "selectCities()" })
#Html.ValidationMessageFor(u => u.State, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(u => u.City, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(u => u.City,
new SelectList(Enumerable.Empty<SelectListItem>(), "Id", "Name"),
"Choose City",
new { #class = "form-control" })
#Html.ValidationMessageFor(u => u.City, "", new { #class = "text-danger" })
</div>
</div>
function selectCities() {
debugger;
var stateId = $("#State").val();
$.ajax({
url: '/Home/selectCities',
type: 'POST',
datatype: 'application/json',
contentType: 'application/json',
data: JSON.stringify({ stateId: +stateId }),
success: function (result) {
$("#City").html("");
$("#City").append
($('<option></option>').val(null).html("---choose City---"));
$.each($.parseJSON(result), function (i, cty)
{ $("#City").append($('<option></option>').val(cty.Id).html(cty.Name)) })
},
error: function () { alert("Error !") },
});
}
The partial code of the controller is this :
private void Fill_StateDropDownList()
{
var st = from d in db.States
orderby d.Name
select d;
ViewBag.State = st.ToList();
}
[HttpPost]
public ActionResult selectCities(string stId)
{
List < City > lstcity = new List < City > ();
int stateiD = Convert.ToInt32(stId);
lstgrupet = (from d in db.Citys
where d.StateID==stateiD
select d).ToList();
string result= JsonConvert.SerializeObject(lstgrupet, Formatting.Indented,
new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore});
return Json(result, JsonRequestBehavior.AllowGet);
}
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
TheObject obj = db.TheObjects.Find(id);
if (obj == null)
{
return HttpNotFound();
}
Fill_StateDropDownList()
return View(obj);
}
[HttpPost, ActionName("Edit")]
[ValidateAntiForgeryToken]
public ActionResult EditPost(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var theobjectToUpdate = db.TheObjects.Find(id);
if (TryUpdateModel(theobjectToUpdate, "",
new string[] { "Name","StateId","CityId" }))
{
try
{
db.SaveChanges();
return RedirectToAction("Index");
}
catch (Exception)
{
ModelState.AddModelError("", "Error.");
}
}
Fill_StateDropDownList()
return View(theobjectToUpdate);
}
actually SelectList has a construct with a parameter called selectedValue
now you should know how to do it
in edit View
<div class="form-group">
#Html.LabelFor(u => u.State, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(u => u.State,
new SelectList(ViewBag.State, "Id", "Name", Model.State),
"Choose State",
new { #class = "form-control", #onchange = "selectCities()" })
#Html.ValidationMessageFor(u => u.State, "", new { #class = "text-danger" })
</div>
</div>
You already have the saved state and city values. All you have to do is to load the subset of cities based on the saved state id and use that collection to render the dropdown for cities
The DropDownListFor helper method will select the corresponding option from the SELECT element as long as the view model's City property value matches with one of the option's value attribute value.
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
TheObject obj = db.TheObjects.Find(id);
if (user == null)
{
return HttpNotFound();
}
Fill_StateDropDownList()
FillCities(obj.State);
return View(obj);
}
private void FillCities(int stateId)
{
ViewBag.CityList = db.Cities
.Where(g => g.StateId== stateId)
.Select(f => new SelectListItem() {
Value = f.Id.ToString(),
Text = f.Name })
.ToList();
}
Make an adjustment to the view
var cityList = new List<SelectListItem>();
if (ViewBag.CityList != null)
{
cityList =ViewBag.CityList as List<SelectListItem>;
}
#Html.DropDownListFor(u => u.City, cityList , "Choose City")
Another option is to make an ajax call on the page load (document ready to get the cities based on the value of state dropdown). It gets complicated if you have multiple nested dropdowns.(ends up in callback hell)

how to populate text boxes based on dropdownlist selection mvc

I'm new to MVC, and very new to JQuery. I'm attempting to populate textboxes based on a dropdownlist selection. My Product model contains the fields ProductId, Name, and Price. I want to populate the ProductId and Price fields in my QuoteDetails based upon the product Name chosen. My controller action is as follows:
public ActionResult AddProduct(int quoteId, int quoteDetailId)
{
var items = db.Products.ToList();
ViewBag.ProductData = items;
ViewData["QuoteId"] = quoteId;
ViewData["QuoteDetailId"] = quoteDetailId;
return PartialView("EditQuoteDetail", new QuoteDetail { QuoteId = quoteId, QuoteDetailId = quoteDetailId, ProductId = 1, ProductName = " ", Amount = 1, ListPrice = 0, Discount = 0, Price = 0 });
}
The relevant portion of the partial view EditQuoteDetail is as follows:
#Html.HiddenFor(model => model.QuoteId, new { htmlAttributes = new { #class = "form-control" } })
#Html.HiddenFor(model => model.QuoteDetailId, new { htmlAttributes = new { #class = "form-control" } })
#Html.EditorFor(model => model.ProductId, new { htmlAttributes = new { #id="ProductId", #class = "form-control" } })
#Html.DropDownList("ProductName", new SelectList(ViewBag.ProductData, "Name", "Name"), new { #id = "ProductName" })
#Html.EditorFor(model => model.Amount, new { htmlAttributes = new { #class = "form-control" } })
#Html.EditorFor(model => model.ListPrice, new { htmlAttributes = new { #id="Price", #class = "form-control" } })
#Html.EditorFor(model => model.Discount, new { htmlAttributes = new { #class = "form-control" } })
#Html.EditorFor(model => model.Price, new { htmlAttributes = new { #class = "form-control" } })
The script I am using to attempt to populate the ProductId and Price fields is as follows:
<script type="text/javascript">
$(document).ready(function () {
$('#ProductName').change(function () {
$('#ProductId').val($(this).val());
$('#Price').val($(this).val());
});
});
</script>
But when I make the dropdown list selection, nothing happens. What am I doing wrong? Any help would be much appreciated.
Here's what I think is happening...
(1) #Html.DropDownList("ProductName", new SelectList(ViewBag.ProductData, "Name", "Name"), new { #id = "ProductName" })
This line creates a <select> html element with an id of "ProductName" as expected; though the value of the options within that list are text values. Because you are using the "Name" for both the value and text of the option. For example:
<select id="ProductName" name="ProductName">
<option value="Product 1">Product 1</option>
<option value="Product 2">Product 2</option>
</select>
(2) #Html.EditorFor(model => model.ProductId, new { htmlAttributes = new { #id="ProductId", #class = "form-control" } })
Since you are using the EditorFor Html helper, it is trying to validate an integer (I assume) of the ProductId. Your javascript is trying to insert a String, like "Product 1".
(3) #Html.EditorFor(model => model.ListPrice, new { htmlAttributes = new { #id="Price", #class = "form-control" } })
This has a slightly different issue. The ID of the HTML element will default to "ListPrice" and not be overridden by your #id property in the htmlAttributes object. Side question, do you mean to put #id = "Price" on the "ListPrice" element? Even if you fixup the ID attributes of these elements, you may still run into the data type issue from (2) above.
Try switching the target element to a TextBoxFor as a quick test.
The problem is not in the script you are populating dropdown
ViewBag.ProductData, "Name", "Name" by Name so the id of the dropdown will also be its Name and also ProductId and Price both are int so you cannot set text value in int field
So you should set the ViewBag.ProductData, "Id", "Name" when ever you will run the script it will get the int value of productId
Edit
if you want to get the data based on your Product id you have to make ajax call for that in jquery and you have to make action for that in controller
[HttpPost]
public ActionResult GetProduct(int pId)
{
var data = db.Products.Find(id);
return Json(data);
}
and your view would be
#model CMSUsersAndRoles.Models.QuoteDetail
#{
ViewBag.Title = "EditQuoteDetail";
Layout = null;
}
#{
var quoteId = (int)ViewData["QuoteId"];
var quoteDetailId = (int)ViewData["QuoteDetailId"];
}
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<div id="row">
<table>
#using (Html.BeginCollectionItem("quoteDetail"))
{
<tr>
#Html.HiddenFor(model => model.QuoteId, new { htmlAttributes = new { #class = "form-control" } })
#Html.HiddenFor(model => model.QuoteDetailId, new { htmlAttributes = new { #class = "form-control" } })
#Html.TextBoxFor(model => model.ProductId, new { htmlAttributes = new { #id="ProductId", #class = "form-control" } })
#Html.DropDownList("ProductList", new SelectList(ViewBag.ProductData, "ProductId", "Name"), new { #id = "ProductList" })
#Html.EditorFor(model => model.Amount, new { htmlAttributes = new { #class = "form-control" } })
#Html.TextBoxFor(model => model.Price, new { htmlAttributes = new { #id="Price", #class = "form-control" } }
#Html.EditorFor(model => model.Discount, new { htmlAttributes = new { #class = "form-control" } })
#Html.EditorFor(model => model.ListPrice, new { htmlAttributes = new { #class = "form-control" } })
#Ajax.ActionLink(" ", "DeleteProduct", "QuoteViewModel", new { quoteId = Model.QuoteId, quoteDetailId = (Model.QuoteDetailId) },
new AjaxOptions
{
HttpMethod = "POST",
Confirm = "Are you Sure You Want to Delete " + Model.ProductName,
OnSuccess = "RemoveRow"
},
new { #class = "btn btn-danger glyphicon glyphicon-trash" })
</tr>
}
</table>
</div>
<script type="text/javascript">
$(document).ready(function () {
$('#ProductList').change(function () {
$.post("/QuoteViewModel/GetProduct", { pId: $(this).val() }, function (data) {
$('#ProductId').val(data.ProductId);
$('#Price').val(data.Price);
});
});
});
</script>
</body>
</html>
At last, I found an answer. travis.js started me on the right path when he said the BeginCollectionItem helper was overtaking my HTML, so I had to use id contains syntax to make it work. The working jQuery (in the parent view) is as follows:
<script type="text/javascript">
$(document).ready(function () {
$(document).on("change", '[id*="ProductList"]', function () {
$.post("/QuoteViewModel/GetProduct", { pId: $(this).val() }, function (data) {
$("[id*='ProductId']").val(data.ProductId);
$("[id*='Price']").val(data.Price);
});
});
});
</script>
And the controller action (thanks Usman) is as follows:
[HttpPost]
public ActionResult GetProduct(int pId)
{
var data = db.Products.Find(pId);
return Json(data);
}
Whew!

How can I change 2 textboxes when I select an option from dropdown

I would like to change two textboxes when I select option from dropdown but I don't know how can I do it.
I'm using dbml file for connecting to other database. I would like to use 2 properties for 2 textboxes = STOK_FIYAT and STOK_KODU.
private BETASYSEntities db = new BETASYSEntities();
private NETSISDataContext netsisdb = new NETSISDataContext();
public ActionResult Olustur(int FormulID)
{
FormulasyonAyrintilari formulasyonayrintilari = new FormulasyonAyrintilari();
formulasyonayrintilari.FormulID = FormulID;
ViewBag.StokAdi = new SelectList(netsisdb.TBLSTSABIT, "STOK_ADI", "STOK_ADI");
return PartialView("_Olustur", formulasyonayrintilari);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Olustur([Bind(Include = "FormulAyrintilariID,FormulID,StokAdi,StokKodu,StokBirim,StokMiktar,StokFiyat")] FormulasyonAyrintilari formulasyonayrintilari)
{
if (ModelState.IsValid)
{
db.FormulasyonAyrintilari.Add(formulasyonayrintilari);
db.SaveChanges();
string url = Url.Action("Index", "FormulasyonAyrintilari", new { id = formulasyonayrintilari.FormulID });
return Json(new { success = true, url = url });
}
ViewBag.StokAdi = new SelectList(netsisdb.TBLSTSABIT, "STOK_ADI", "STOK_KODU", formulasyonayrintilari.StokAdi);
return PartialView("_Olustur", formulasyonayrintilari);
}
#Html.DropDownList("StokAdi", null, "Lütfen Seçin", htmlAttributes: new { #class = "form-control col-md-3 select2", autocomplete = "off" })
#Html.EditorFor(model => model.StokKodu, new { htmlAttributes = new { #class = "form-control", autocomplete = "off" } })
#Html.EditorFor(model => model.StokFiyat, new { htmlAttributes = new { #class = "form-control", autocomplete = "off" } })
Create an action that returns JsonResult which will receive the value STOK_ADI and returns a JSON Object that has STOK_KODU and STOK_FIYAT
public JsonResult GetValuesForSTOK_ADI(string STOK_ADI)
{
//get the values from the DB for the provided STOK_ADI
return Json(new {STOK_KODU ="value from db",STOK_FIYAT="value from db"},JsonRequestBehavior.AllowGet));
}
In your view, change the declaration for the drop down to add an onchange event that will call the action
#Html.DropDownList("StokAdi", null, "Lütfen Seçin", htmlAttributes: new { #class = "form-control col-md-3 select2", autocomplete = "off",onchange="updateTextBoxes()"})
at the end of the file, create the below javascript function
<script>
function updateTextBoxes()
{
var selectedSTOK_ADI = $("#StokAdi").val();
$.ajax('#Url.Action("GetValuesForSTOK_ADI","ControllerName")').then(function(data){
$("#StokKodu").val(data.STOK_KODU);
$("#StokFiyat").val(data.STOK_FIYAT);
});
}
</script>

Categories

Resources