I'm trying to use cascaded Drop Down for a project, but with a bit of a twist. For Power Users, they can enter a stock code and search. The retrieved information then updates the Parent Drop Down and the cascaded Drop Down selection.
Using a click event, I can search the entered value and it returns all the needed information. I can update the Parent to Display the correct information, But unable to get the child to display. It's stuck on showing " -- Select --" Populating the drop down's with data to select from works great. Could really use some insight and help.. Got myself stumped on the child. Thanks..
I followed this example to setup the Dropdowns. asp.net MVC cascading dropdown lists
<Controller>
public ActionResult Create()
{
ViewData["User"] = User.Identity.GetUserName();
BindPartType();
return View();
}
public void BindPartType()
{
partsmanagementEntities5 parttypelist = new partsmanagementEntities5(); //Parts
var parttype = parttypelist.parttypes.ToList();
List<SelectListItem> pli = new List<SelectListItem>();
pli.Add(new SelectListItem { Text = "--Select Catagory--", Value = "0" });
foreach (var m in parttype)
{
pli.Add(new SelectListItem { Text = m.PartType1, Value = m.idPartType.ToString() });
ViewBag.PartType = pli;
}
}
public JsonResult GetInventory(int? id)
{
partsmanagementEntities5 partlist = new partsmanagementEntities5();
var ddlpart = partlist.parts.Where(x => x.PartType == id).ToList();
List<SelectListItem> lipart = new List<SelectListItem>();
lipart.Add(new SelectListItem { Text = "--Select Inventory--", Value = "0" });
if (ddlpart != null)
{
foreach (var x in ddlpart)
{
lipart.Add(new SelectListItem { Text = x.PartDescription, Value = x.idParts.ToString() });
}
}
return Json(new SelectList(lipart, "Value", "Text", JsonRequestBehavior.AllowGet));
}
public JsonResult Check(string id)
{
partsmanagementEntities5 partlist = new partsmanagementEntities5();
StringBuilder test = new StringBuilder();
if(id != null && id != "")
{
foreach (char c in id)
{
if (!char.IsNumber(c))
test.Append(c);
}
var ddlpartnumber = partlist.parts.Where(x => x.PartNumber == id.ToString());
PartDetails li = new PartDetails();
foreach (var item in ddlpartnumber.ToList())
{
li.PartNumber = item.PartNumber;
li.PartPrice = item.PartPrice;
li.idParts = item.idParts;
li.EHF = item.EHF;
li.PartDescription = item.PartDescription;
li.PartImage = item.PartImage;
li.partImageContentType = item.partImageContentType;
li.unit = item.unit;
li.PartType = item.PartType;
li.VendorPartNumber = item.VendorPartNumber;
}
return Json(li, JsonRequestBehavior.AllowGet);
}
return Json("", JsonRequestBehavior.AllowGet);
}
<View>
<table>
<tr>
<td style="padding-left:0.8ex;padding-top:0.8ex">#Html.Label("Catagory: ")</td>
<td>
#Html.DropDownListFor(model => model.PartType, ViewBag.PartType as List<SelectListItem>, new { style = "width: 800px;" })
#Html.ValidationMessageFor(model => model.PartType, "", new { #class = "text-danger" })
</td>
<td style="padding-left:6ex;padding-top:0.8ex"></td>
</tr>
<tr>
<td style="width:1px;white-space:nowrap;padding-left:0.8ex">#Html.Label("Inventory: ")</td>
<td>
#Html.DropDownListFor(model => model.PartNumber, new SelectList(string.Empty, "Value", "Text"), "--Select Inventory--", new { style = "width:900px" })
#Html.ValidationMessageFor(model => model.PartNumber, "", new { #class = "text-danger" })
</td>
</tr>
<tr>
<td style="width:1px;white-space:nowrap;padding-left:6ex">#Html.Label("Or choose:")</td>
</tr>
<tr>
<td style="width:1px;white-space:nowrap;padding-left:0.8ex">#Html.Label("Enter Valid Part #: ")</td>
<td><input type="text" name="CheckPartNumber" id="CheckPartNumber"> <input type="button" id="Search" value="Search" class="btn btn-default" />
</tr>
</table>
<script src="~/Scripts/jquery-3.0.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#PartType").change(function () {
$("#PartNumber").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("GetInventory", "partrequests")',
dataType: 'json',
data: { id: $("#PartType").val() },
success: function (PartNumber) {
$.each(PartNumber, function (i, PartNumber) {
$("#PartNumber").append('<option value="'
+ PartNumber.Value + '">'
+ PartNumber.Text + '</option>');
});
},
error: function (ex) {
alert('Failed.' + ex);
}
});
return false;
})
});
$(document).ready(function () {
$("#Search").click(function () {
$.ajax({
type: 'POST',
url: '#Url.Action("Check","partrequests")',
dataType: 'json',
data: { id: $("#CheckPartNumber").val() },
success: function (Data) {
var selectedValue = Data.PartType
$('#PartType option').map(function () {
if ($(this).val() == selectedValue) return this;
}).attr('selected', 'selected').change();
var selectedValue2 = Data.idParts;
$('#PartNumber option').map(function () {
if ($(this).val() == selectedValue2) return this;
}).attr('selected', 'selected');
},
error: function (ex) {
alert('Failed.' + ex);
}
});
return false;
})
});
</script>
Related
I have a main view. Once the posting is done, it will render a partial view in the main view.
My partial view has a cascading dropdown list that changes the 2nd DropdownList items based on the selected value from the 1st DropdownList.
Here is my Dropdown in my Partial View.
#model MigratingDB.Models.ViewModel
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<div>
#Html.DropDownListFor(m => m.DropdownViewModel.SelectedValue1,
Model.DropdownViewModel.List1, "Select",htmlAttributes: new { #class = "form-control", #id = "ddl1" })
</div>
<div>
#Html.DropDownListFor(m => m.DropdownViewModel.SelectedValue2,
Model.DropdownViewModel.List2 = new SelectList(Enumerable.Empty<SelectListItem>()), "Select",
htmlAttributes: new { #class = "form-control", #id = "ddl2" })
</div>
The script I tried based from this.
<script>
$(function () {
$('#ddl1').change(function () {
$("#ddl2").empty();
var selectedValue = $(this).val();
$.ajax({
url: '#Url.Action("Getddl2Items", "Controller")',
type: "POST",
dataType: 'json',
data: { id: selectedValue },
success: function (value) {
$.each(value, function (i, val) {
$("#ddl2").append('<option value="' + val.Value + '">' +
val.Text + '</option>');
});
},
error: function (ex) {
alert('Failed' + ex);
},
});
});
});
</script>
In my Controller:
[HttpPost]
public ActionResult Foo (ViewModel vm)
{
// Dropdownlist
var list1 = // get items frop ddl1
vm.DropdownViewModel.List1= new SelectList(list1, "Value", "Text");
return PartialView("_PartialView", vm);
}
// Get ddl2 Items
public JsonResult Getddl2Items (int id)
{
var ViewModel = new ViewModel();
var list2= // get ddl2 items from the database
ViewModel.DropdownViewModel.List2= new SelectList(list2, "Value", "Text");
return Json(ViewModel.DropdownViewModel.List2, JsonRequestBehavior.AllowGet);
}
Every time I tried to select a value from the ddl1, it errors and show
Failed [object Object].
What causes this?
This is a long post that I tested and works. Since it is long, you can pick out the parts you need. Let's work together to figure out why it is not working for you.
This will be your table and data creation:
--Use your database name instead of Breaz
USE [Breaz]
GO
/****** Object: Table [dbo].[tblCity] Script Date: 7/17/2017 9:46:31 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tblCity](
[Cityid] [int] NOT NULL,
[CityName] [nvarchar](50) NULL,
[stateid] [int] NOT NULL
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[tblState] Script Date: 7/17/2017 9:46:31 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tblState](
[stateid] [int] NOT NULL,
[statename] [nvarchar](50) NULL,
PRIMARY KEY CLUSTERED
(
[stateid] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
INSERT [dbo].[tblCity] ([Cityid], [CityName], [stateid]) VALUES (1, N'Phoenix', 1)
INSERT [dbo].[tblCity] ([Cityid], [CityName], [stateid]) VALUES (2, N'Las Angeles', 2)
INSERT [dbo].[tblState] ([stateid], [statename]) VALUES (1, N'Arizona')
INSERT [dbo].[tblState] ([stateid], [statename]) VALUES (2, N'California')
ALTER TABLE [dbo].[tblCity] WITH CHECK ADD FOREIGN KEY([stateid])
REFERENCES [dbo].[tblState] ([stateid])
GO
Create your edmx, by going through visual studio wizard.
Create your view model:
//user your namespace
namespace Testy20161006.Models
{
public class Registration
{
[Required(ErrorMessage = "Enter State")]
public string State { get; set; }
[Required(ErrorMessage = "Enter City")]
public string City { get; set; }
}
}
Your controller/classes:
public class HomeController : Controller
{
public JsonResult getCity(int id)
{
//use your dbcontext name from edmx wizard
using (BreazEntities33 objEF = new BreazEntities33())
{
var ddlCity = objEF.tblCities.Where(x => x.stateid == id).ToList();
List<SelectListItem> licities = new List<SelectListItem>();
licities.Add(new SelectListItem { Text = "--Select State--", Value = "0" });
if (ddlCity != null)
{
foreach (var x in ddlCity)
{
licities.Add(new SelectListItem { Text = x.CityName, Value = x.Cityid.ToString() });
}
}
return Json(new SelectList(licities, "Value", "Text", JsonRequestBehavior.AllowGet));
}
}
[HttpPost]
public ActionResult IndexStackOverflow(Registration registration)
{
//put breakpoint here to see values coming back from view
return View(registration);
}
//use your name of action that starts the process, named in routeconfig.cs
public ActionResult IndexStackOverflow()
{
bindState();
return View();
}
public void bindState()
{
//use your dbcontext name from edmx wizard
using (BreazEntities33 objEF = new BreazEntities33())
{
var state = objEF.tblStates.ToList();
List<SelectListItem> li = new List<SelectListItem>();
li.Add(new SelectListItem { Text = "--Select State--", Value = "0" });
foreach (var m in state)
{
li.Add(new SelectListItem { Text = m.statename, Value = m.stateid.ToString() });
ViewBag.state = li;
}
}
}
Here is your view:
#model Testy20161006.Models.Registration
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>IndexStackOverflow</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#State").change(function () {
$("#City").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("getcity")',
dataType: 'json',
data: { id: $("#State").val() },
success: function (city) {
$.each(city, function (i, city) {
$("#City").append('<option value="'
+ city.Value + '">'
+ city.Text + '</option>');
});
},
error: function (ex) {
alert('Failed.' + ex);
}
});
return false;
})
});
</script>
</head>
<body>
#using (Html.BeginForm())
{
<div class="container">
<div class="row">
<div class="form-group">
#Html.LabelFor(model => model.State, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.State, ViewBag.state as List<SelectListItem>, new { style = "width: 200px;" })
#Html.ValidationMessageFor(model => model.State, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="form-group">
#Html.LabelFor(model => model.City, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.City, new SelectList(string.Empty, "Value", "Text"), "--Select City--", new { style = "width:200px" })
#Html.ValidationMessageFor(model => model.City, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div><input type="button" value="submit" /></div>
}
</body>
</html>
Here is an example that returns Json value from a SelectListItem in a ViewModel.
public class ReturnJsonVM
{
public List<SelectListItem> licities = new List<SelectListItem>();
}
public class HomeController : Controller
{
//use your name of action that starts the process, named in routeconfig.cs
public string IndexStackOverflow()
{
using (BreazEntities33 objEF = new BreazEntities33())
{
var ddlCity = objEF.tblCities.Where(x => x.stateid == 1).ToList();
List<SelectListItem> licities = new List<SelectListItem>();
ReturnJsonVM returnJsonVM = new ReturnJsonVM();
if (ddlCity != null)
{
foreach (var x in ddlCity)
{
returnJsonVM.licities.Add(new SelectListItem { Text = x.CityName, Value = x.Cityid.ToString() });
}
}
string json = JsonConvert.SerializeObject(returnJsonVM.licities);
//put your break point here to see example that return Json value from SelectListItem in ViewModel
return json;
}
}
In this MVC application I've created cascading dropdown list i.e it will first populate countries list and after selecting country jquery's onchange event is called which will fetch the further states from the controller which further gets those data by edmx entity model in database.i have used ajax request to call the JSON method in this.After selecting states the new dropdown list would get activated for selecting Cities.Whenever I select countries from the drop down an alertbox pops out and says states retrieving failed.[object][object] also I didn't create relationship between tables as foreign key is that necessary
Location Controller:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplication3.Controllers
{
public class LocationController : Controller
{
//
// GET: /Location/
public ActionResult Index()
{
TestDBEntities db = new TestDBEntities();
ViewBag.Country = new SelectList(db.tblCountries, "CountryID", "CountryName");
return View();
}
public JsonResult GetState(string id)
{
List<SelectListItem> states = new List<SelectListItem>();
var stateList = this.Getstatevalue(Convert.ToInt32(id));
var stateData = stateList.Select(m => new SelectListItem()
{
Text = m.StateName,
Value = m.StateID.ToString(),
});
return Json(stateData, JsonRequestBehavior.AllowGet);
}
public IList<tblState> Getstatevalue(int CountryId)
{
TestDBEntities db = new TestDBEntities();
return db.tblStates.Where(m => m.CountryID == CountryId).ToList();
}
public JsonResult GetCity(string id)
{
List<SelectListItem> cities = new List<SelectListItem>();
var cityList = this.Getcityvalue(Convert.ToInt32(id));
var cityData = cityList.Select(m => new SelectListItem()
{
Text = m.CityName,
Value = m.CityID.ToString(),
});
return Json(cityData, JsonRequestBehavior.AllowGet);
}
public IList<tblCity> Getcityvalue(int StateId)
{
TestDBEntities db = new TestDBEntities();
return db.tblCities.Where(m => m.StateID == StateId).ToList();
}
}
}
Index.cshtml view
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>EmployeeData</legend>
<div class="editor-label">
#Html.Label("Country")<br />
</div>
<div>
#Html.DropDownList("Country", ViewBag.Country as SelectList, "-- Please Select a Country --", new { style = "width:150px", #id = "Country" })
</div>
<div class="editor-label">
<br />
#Html.Label("State")<br />
</div>
<div>
#Html.DropDownList("State", new SelectList(string.Empty, "Value", "Text"), "-- Please select a State --",
new { style = "width:150px", #class = "dropdown1" })
</div>
<div class="editor-label">
<br />
#Html.Label("City")<br />
</div>
<div>
#Html.DropDownList("City", new SelectList(string.Empty, "Value", "Text"), "-- Please select a city --",
new { style = "width:150px", #class = "dropdown2", #id = "City" })
</div>
<p>
<input type="button" onclick="ddlInsert()" value="Submit" />
</p>
</fieldset>
}
javascript code :
<script type="text/javascript">
$(document).ready(function () {
// this is Country Dropdown Selectedchange event
$("#Country").change(function () {
$("#State").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("Getstates")', // here we are Calling json method
dataType: 'json',
data: { id: $("#Country").val() },
// Get Selected Country ID.
success: function (states) {
$.each(states, function (i, state) {
$("#State").append('<option value="' + state.Value + '">' +
state.Text + '</option>');
});
},
error: function (ex) {
alert(' states retrieving fail.' + ex);
}
});
return false;
})
$("#State").change(function () {
$("#City").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("GetCities")', // here we are Calling json method
dataType: 'json',
data: { id: $("#State").val() },
// Get Selected Country ID.
success: function (cities) {
$.each(cities, function (i, city) {
$("#City").append('<option value="' + city.Value + '">' +
city.Text + '</option>');
});
},
error: function (ex) {
alert(' city retrieving fail.' + ex);
}
});
return false;
})
});
</script>
When I select a country in it No state gets loaded or populated into the dropdown list for states.
I am trying to generate checkbox dynamically(image: Select Report) on change/click event of another checkbox(image:Report Type) by using pertial view.On page load I made one checkbox true and generate checkbox dynamically based on it's data.
Here is the image of this page:
But when I click another checkbox, It's not updating the panel and showing previous data. Here is the image:
Here is my Index Page
#using RSDMS.ViewModel
#{
ViewBag.Title = "Reports";
Layout = "~/Views/ReportModule/_ReportModule.cshtml";
var ReportTypeList = (IEnumerable<VmReportType>)ViewBag.ReportType;
}
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<h2 style="color: #317eac; margin-top: -8% !important">Reports </h2>
<div class="panel panel-info class" style="margin-top: 0 !important;width: 99%">
<div class="panel-heading" style="background: #1995dc; text-decoration: solid;">Report Type</div>
<div class="panel-body reportTypeDiv">
#using (#Html.BeginForm(new { id = "reportType" }))
{
if (ReportTypeList != null)
{
<table>
<tr>
#foreach (var p in ReportTypeList)
{
<td>
#Html.CheckBoxFor(it => p.IsCheck, new { Style = "vertical-align:3px", value = p.Id, #class = "checkbox"})
</td>
<td>
#Html.HiddenFor(it => p.Id)
#Html.DisplayFor(it => p.Name)
</td>
}
</tr>
</table>
}
}
</div>
</div>
<div class="panel panel-info class" style="height: 650px; width: 300px">
<div class="panel-heading" style="background: #1995dc; text-decoration: solid;">Select Report</div>
<div class="panel-body listReport" id="lstReport">
#Html.Partial("_ListOfReports")
</div>
<div class="CrystalReport">
<iframe class="CrystalReportViewer1"> </iframe>
</div>
</div>
<script type="text/javascript">
$(function () {
$('.checkbox').change(function () {
var selectedValue = this.value;
$('input:checkbox:checked').each(function () {
if (this.value == selectedValue) {
$(this).attr('checked', 'checked');
} else {
$(this).removeAttr('checked');
}
});
$(this).attr('checked', 'checked');
$.ajax({
url: '#Url.Action("LoadReports", "Reports", new AjaxOptions { UpdateTargetId = "lstReport" })',
type: 'POST',
data: { Id: selectedValue },
success: function () {
swal("ok", " ", "success");
},
error: function () {
sweetAlert("not ok", " ", "error");
}
});
});
});
</script>
Here is my Partial Page
#using RSDMS.ViewModel
#{
var ReportList = (IEnumerable<VmReport>)ViewBag.ListOfReports;
}
#using (#Html.BeginForm())
{
if (ReportList != null)
{
foreach (var q in ReportList)
{
<table id="selectReport">
<tr>
<td>
#Html.CheckBoxFor(it => q.IsChecked, new { Style = "vertical-align:3px}", type = "checkbox", value = q.ReportId, #class ="checkboxReport" })
</td>
<td>
#Html.HiddenFor(it => q.ReportId)
#Html.DisplayFor(it => q.Name)
</td>
</tr>
</table>
}
}
}
Here is my controller's Code
public ActionResult Index()
{
var listReportType = new List<VmReportType>
{
new VmReportType{Id = "A", Name = "A-Road Related", IsCheck = true},
new VmReportType{Id = "B", Name = "B- Road+Structure Related", IsCheck = false},
new VmReportType{Id = "C", Name = "C- Need, Scheme & Progress Related", IsCheck = false},
new VmReportType{Id = "D", Name = "D- GC/RM/etc. Related", IsCheck = false},
new VmReportType{Id = "E", Name = "E- RIMMU", IsCheck = false}
};
ViewBag.ReportType = listReportType;
LoadReports("A");
return PartialView();
}
[HttpPost]
public ActionResult LoadReports(string id)
{
var reports = _manager.LoadReports(id);
ViewBag.ListOfReports = reports;
return PartialView("_ListOfReports", ViewBag.ListOfReports);
}
Here is the image of ajax response
Create click (2nd Partial view) is not hit into action controller. I have used two partial view. I tried the below steps. please see the attached screen shot
While clicking Add button (Index), Dropdown Selected value is added into partial view(1st partial view)
On Click Edit, another partial view(2nd) is loaded into div.
2'nd PV (Create) click, i'm planning to validate model(SubmitReview), generate xml and update to previous partial view, but this is not happening. please see the below code and suggest me how to achieve?
public ActionResult Index()
{
var DBQList = DBActivity.Getdbqlist();
DBQModel viewmodel = new DBQModel();
var DBQSelectList = new SelectList(DBQList, "DBQ_ID", "DBQ_Name", "IsSelected");
viewmodel.selectList = DBQSelectList;
Session["Session_DBQModel"] = viewmodel;
return View(viewmodel);
}
[HttpPost]
public ActionResult Index(DBQModel dbqModel)
{
if (ModelState.IsValid)
{
//
}
var mdl = (DBQModel)Session["Session_DBQModel"];
var selectedvalue = Convert.ToInt32(Request.Form["SelectedId"].ToString());
var rows = DBActivity.Getdbqlist().FirstOrDefault(x => x.DBQ_ID == selectedvalue);
if (rows != null)
{
DBQTable tbl = new DBQTable();
tbl.DBQ_ID = rows.DBQ_ID;
tbl.DBQ_Name = rows.DBQ_Name;
tbl.DBQ_Desc = rows.DBQ_Desc;
tbl.VAFormNo = rows.VAFormNo;
mdl.dbqTable.Add(tbl);
}
Session["Session_DBQModel"] = mdl;
return View(mdl);
}
public PartialViewResult LoadDBQ(int id)
{
if (id==1)
{
EatingDisorder eatingDisorder = new EatingDisorder();
return PartialView("_EatingDisorderPV", eatingDisorder);
}
return PartialView("_DefaultPV");
}
[HttpPost]
public ActionResult SubmitReview(EatingDisorder _model)
{
try
{
if (!ModelState.IsValid)
{
string messages = string.Join("; ", ModelState.Values
.SelectMany(x => x.Errors)
.Select(x => x.ErrorMessage));
throw new Exception("Please correct the following errors: " + Environment.NewLine + messages);
}
if (_model.s1_Bulima)
{
if ((_model.s1_Bulima_Date != null) && (string.IsNullOrEmpty(_model.s1_Bulima_ICD)) && (!string.IsNullOrEmpty(_model.s1_Bulima_Name)))
{
//ok
}
else
{
ModelState.AddModelError("s1_Bulima_Date", "s1_Bulima_Date is required.");
ModelState.AddModelError("s1_Bulima_ICD", "s1_Bulima_ICD is required.");
ModelState.AddModelError("s1_Bulima_Name", "s1_Bulima_Name is required.");
}
}
//save to db
//return Json(new { Result = "OK" });
}
catch (Exception ex)
{
//return Json(new { Result = "ERROR", Message = ex.Message });
ModelState.AddModelError("", ex.Message);
}
return PartialView("_EatingDisorderPV", _model);
}
Iindex.cshtml
#model WebApplication1.Models.DBQModel
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
#Html.DropDownListFor(n => n.SelectedId, Model.selectList, "Please select dbq", new { #class = "from-control col-md-4" })
<input type="submit" value="Add" class="btn btn-default" />
#Html.Partial("_DBQGridPV", Model.dbqTable)
<div id="DBQHolder"></div>
}
_DBQGridPV.cshtml
#model IEnumerable<WebApplication1.Models.DBQTable>
<table class="table">
<tr>
<th>#Html.DisplayNameFor(model => model.DBQ_ID)</th>
.....
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>#Html.DisplayFor(modelItem => item.DBQ_ID)</td>
.....
<td>
#Ajax.ActionLink("Edit", "LoadDBQ", new { id = item.DBQ_ID },
new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "DBQHolder", InsertionMode = InsertionMode.Replace })|
#Html.ActionLink("Delete", "DeleteDBQ", new { id = item.DBQ_ID })
</td>
</tr>
}
</table>
_EatingDisorderPV.cshtml
#model WebApplication1.Models.EatingDisorder
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
.....
<input type="submit" value="Create" />
}
I have three dropdown List.The First action method for City drop down is as---
public ActionResult Create()
{
List<SelectListItem> li = new List<SelectListItem>();
li.Add(new SelectListItem { Text = "Select your City", Value = "----" });
li.Add(new SelectListItem { Text = "Faridabaad", Value = "Faridabaad" });
li.Add(new SelectListItem { Text = "Greater Noida", Value = "Greater Noida" });
li.Add(new SelectListItem { Text = "Gurgaon", Value = "Gurgaon" });
li.Add(new SelectListItem { Text = "Noida", Value = "Noida" });
li.Add(new SelectListItem { Text = "New Delhi", Value = "New Delhi" });
ViewData["City"] = li;
return View();
}
then i have action method for my Locality drop down list which changes as we change city name like this------
public JsonResult LoadLocalities(string id)
{
List<SelectListItem> localities = new List<SelectListItem>();
switch(id)
{
case"New Delhi":
localities.Add(new SelectListItem { Text = "Select your locality", Value = "0" });
localities.Add(new SelectListItem{ Text ="East Delhi", Value = "1" });
localities.Add(new SelectListItem{ Text ="West Delhi", Value = "2" });
localities.Add(new SelectListItem{ Text ="North Delhi", Value = "3" });
localities.Add(new SelectListItem { Text = "South Delhi", Value = "4" });
break;
}
return Json(new SelectList(localities, "Value", "Text"));
}
and the action method for the last sub locality drop down which changes with the change in locality name is like this---
public JsonResult LoadSubLocalities(string id)
{
List<SelectListItem> sublocalities = new List<SelectListItem>();
switch (id)
{
case"1":
sublocalities.Add(new SelectListItem { Text = "Select your sublocality", Value = "0" });
sublocalities.Add(new SelectListItem { Text = "Region1", Value = "1" });
sublocalities.Add(new SelectListItem { Text = "Region2", Value = "2" });
break;
}
return Json(new SelectList(sublocalities, "Value", "Text"));
}
now the view page is something like this------
<!DOCTYPE html>
<head>
<title></title>
<script src="~/Scripts/jquery-2.1.4.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
</head>
<body>
<div id="map_canvas" style="width: 800px; height: 700px; float:left"></div>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>Enter the Project Details</legend>
<div class="editor-label">
#Html.LabelFor(model => model.City)
</div>
<div class="editor-field">
#if (ViewData.ContainsKey("City")){
#Html.DropDownListFor(model => model.City, ViewData["City"] as List<SelectListItem>, new { style = "width:250px", #class = "DropDown1"})
#Html.ValidationMessageFor(model => model.City)
}
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Locality)
</div>
<div class="editor-field">
#Html.DropDownList("Locality", new SelectList(string.Empty,"Value","Text"),"Please Select a locality", new { style = "width:250px", #class = "DropDown1" })
#Html.ValidationMessageFor(model => model.Locality)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.SubLocality)
</div>
<div class="editor-field">
#Html.DropDownList("SubLocality", new SelectList(string.Empty, "Value", "Text"), "Please Select a sub locality", new { style = "width:250px", #class = "DropDown1" })
#Html.ValidationMessageFor(model => model.SubLocality)
</div>
<p>
<input type="submit" value="Save Project" />
</p>
</fieldset>
Now my javaScript code is something like this where i have written code to fetch city from controller then change locality as the city name changes and change sub locality name with change in locality name-----
<script type="text/javascript">
$(document).ready(function () {
$("#City").change(function () {
$("#Locality").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("LoadLocalities","Project")',
dataType: 'json',
data: { id: $("#City").val() },
success: function (localities) {
$.each(localities, function (i, locality) {
$("#Locality").append('<option value="' + locality.Value + '">' +
locality.Text + '</option>');
});
},
error: function (ex) {
alert('Failed to retreive Locality.' + ex);
}
});
return false;
})
$("#Locality").change(function () {
$("#SubLocality").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("LoadSubLocalities")',
dataType: 'Json',
data: { id: $("Locality").val() },
success: function (sublocalities) {
$.each(sublocalities, function (i, sublocality) {
$("#SubLocality").append('<option value="' + sublocality.Value + '">' +
sublocality.Text + '</option>');
});
},
error: function (ex) {
alert('Failed to retrieve SubLocality.' + ex);
}
});
return false;
})
});
</script>
}
Now, My problem is that my Locality is working fine with change in city name but SubLocality drop down is not working with change in locality name---
The reason your $("#Locality").change(function () { is not working is because the following line
data: { id: $("Locality").val() },
return undefined. It needs to be
data: { id: $("#Locality").val() }, // add hash
however the correct approach is to use
data: { id: $(this).val() },
in order to avoid traversing the DOM again to get the element with id="Locality"
There are numerous other issues with your code, particularly in respect to validation and returning the view if ModelState is invalid
When generating List<SelectListItem>, do not add the label option
(i.e. sublocalities.Add(new SelectListItem { Text = "Select your
sublocality", Value = "0" });). You are giving the label option a
value which means that its always valid. As it currently is, you may
as well delete the #Html.ValidationMessageFor() associated with
each dropdown.
Never give the SelectList the same name as the property your
binding to (in your case City)
In your LoadLocalities() and LoadSubLocalities() methods you
first create List<SelectListItem> and then create a new
SelectList (which is IEnumerable<SelectListItem>) so its just
unnecessary extra overhead. In any case the client has no knowledge
of what a C# class is and you just returning twice as much data
across the wire as is necessary (the Selected,Disabled and
Group properties which you never use). Instead just pass back a
collection of anonymous objects containing 2 properties (for the
option value and text)