Second DDL not firing - asp.net-mvc

good day, why my second DDL do not fire when I select the Parent dropdown list.
Also can anyone elaborate the script and the [ 0] in the View beside m=>m.StateModel
And for the last question, how can I make this DDL dynamic, How can I populate it using database data?
Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Kaskid.Models
{
public class State
{
public int Id { get; set; }
public string StateName { get; set; }
}
public class City
{
public int Id { get; set; }
public int StateId { get; set; }
public string CityName { get; set; }
}
public class CountryModel
{
public List<State> StateModel { get; set; }
public SelectList FilteredCity { get; set; }
}
}
Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Kaskid.Models;
namespace Kaskid.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
CountryModel objCountryModel = new CountryModel();
objCountryModel.StateModel = new List<State>();
objCountryModel.StateModel = GetAllState();
return View(objCountryModel);
}
[HttpPost]
public ActionResult GetCityByStateId(int stateId)
{
List<City> objCity = new List<City>();
objCity = GetAllcity().Where(m => m.StateId == stateId).ToList();
SelectList obgcity = new SelectList(objCity, "Id", "CityName", 0);
return Json(obgcity);
}
public List<State> GetAllState()
{
List<State> objState = new List<State>();
objState.Add(new State {Id = 0,StateName="Select State"});
objState.Add(new State {Id = 1,StateName = "State 1"});
objState.Add(new State {Id = 2, StateName="State 2"});
objState.Add(new State {Id = 3, StateName="State 3"});
return objState;
}
public List<City> GetAllcity()
{
List<City> objCity = new List<City>();
objCity.Add(new City{Id = 1,StateId = 1, CityName = "City1-1" });
objCity.Add(new City{Id = 2,StateId=2,CityName = "City2-1"});
objCity.Add(new City{Id = 3,StateId=4,CityName="City4-1"});
objCity.Add(new City{Id = 4,StateId=1,CityName="City1-2"});
return objCity;
}
}
}
View
#model Kaskid.Models.CountryModel
#{
ViewBag.Title = "Index";
}
<script language="javascript">
function GetCity(_stateId) {
var procemessage = "<option value='0'> Please wait...</option>";
$('#ddlcity').html(procemessage).show();
var url = "/Home/GetCityByStaeId/";
$.ajax({
url: url,
data: { stateid: _stateId },
cache: false,
type: "POST",
success: function (data) {
var markup = "<option value='0'>Select City</option>";
for (var x = 0; x < data.length; x++) {
markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
}
$('#ddlcity').html(markup).show();
},
error: function (reponse) {
alert("error : " + reponse);
}
});
}
</script>
<h4>
MVC3 Cascading Dropdown List Using Jquery</h4>
#using (Html.BeginForm("", ""))
{
#Html.DropDownListFor(m => m.StateModel[0].Id, new SelectList(Model.StateModel, "Id", "StateName"), new { #id = "ddlstate", #style = "width:200px;", #onchange = "javascript:GetCity(this.value);" })
<br />
<br />
<select id="ddlcity" name="ddlcity" style="width: 200px">
</select>
}

You've got a typo:
var url = "/Home/GetCityByStaeId/";
But your controller action is called GetCityByStateId and not GetCityByStaeId. Also you may take a look at a similar example I once wrote where you could take some ideas about improving your code.

Related

Custom Validation for nested model in .net core

I am trying to validate a nested model using custom validation. But the problem is AttributeAdapterBase.AddValidation function is never called on nested model. However it works well with simple class property
Custom required validation attribute:
public interface IId
{
long Id { get; set; }
}
public class Select2RequiredAttribute : RequiredAttribute
{
public Select2RequiredAttribute(string errorMessage = "") : base()
{
ErrorMessage = errorMessage;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
Type t = value.GetType();
if (typeof(IId).IsAssignableFrom(t))
{
if ((value as IId).Id == 0)
{
return new ValidationResult(ErrorMessage);
}
}
else
{
return new ValidationResult(ErrorMessage);
}
return ValidationResult.Success;
}
}
Attribute adapter base:
public class Select2RequiredAttributeAdapter : AttributeAdapterBase<Select2RequiredAttribute>
{
public Select2RequiredAttributeAdapter(Select2RequiredAttribute attribute, IStringLocalizer stringLocalizer) : base(attribute, stringLocalizer)
{
}
public override void AddValidation(ClientModelValidationContext context)
{
MergeAttribute(context.Attributes, "data-val", "true");
MergeAttribute(context.Attributes, "data-val-select2-required", GetErrorMessage(context));
}
public override string GetErrorMessage(ModelValidationContextBase validationContext)
{
return Attribute.ErrorMessage ?? GetErrorMessage(validationContext.ModelMetadata, validationContext.ModelMetadata.GetDisplayName());
}
}
Adapter provider:
public class Select2RequiredAdapterProvider : IValidationAttributeAdapterProvider
{
private readonly IValidationAttributeAdapterProvider _baseProvider = new ValidationAttributeAdapterProvider();
public IAttributeAdapter GetAttributeAdapter(ValidationAttribute attribute, IStringLocalizer stringLocalizer)
{
if (attribute is Select2RequiredAttribute)
{
return new Select2RequiredAttributeAdapter(attribute as Select2RequiredAttribute, stringLocalizer);
}
else
{
return _baseProvider.GetAttributeAdapter(attribute, stringLocalizer);
}
}
}
Startup.cs:
services.AddSingleton<IValidationAttributeAdapterProvider, Select2RequiredAdapterProvider>();
Model classes:
public interface IBaseBriefViewModel : IId
{
string Name { get; set; }
}
public class BaseBriefViewModel : IBaseBriefViewModel
{
public virtual long Id { get; set; }
public string Name { get; set; }
}
public class UserViewModel
{
public long Id { get; set; }
public string Name { get; set; }
[Select2Required("Branch is required.")]
public BaseBriefViewModel Branch { get; set; }
}
Branch select 2 partial view:
#model DataLibrary.ViewModels.BriefViewModels.BaseBriefViewModel
#{
var elementId = ViewData["ElementId"] != null && !string.IsNullOrEmpty(ViewData["ElementId"].ToString()) ? ViewData["ElementId"].ToString() : "branch-id";
}
<div class="form-group">
<label>Branch: <span class="text-danger"></span></label>
<div class="row">
<div class="#select2Class">
#Html.DropDownListFor(model => model.Id, new List<SelectListItem>() {
new SelectListItem()
{
Value = (Model!=null&&Model.Id>0)?Model.Id.ToString():"",
Text = (Model!=null&&Model.Id>0)?Model.Name:"",
Selected = (Model!=null&&Model.Id>0)?true:false,
}}, new { #id = elementId, #class = "form-control disable-field"})
#Html.ValidationMessageFor(model => model.Id, "", new { #class = "text-danger" })
</div>
</div>
</div>
<script>
$(function () {
var id = "#" + "#elementId";
var url = '/Branch/GetBranchsForSelect2';
var dataArray = function (params) {
params.page = params.page || 1;
return {
prefix: params.term,
pageSize: pageSize,
pageNumber: params.page,
};
};
Select2AutoCompleteAjax(id, url, dataArray, pageSize, "---Branch---");
});
</script>
All this code works well for server side. But for better user experience I want to show error before submitting form. How can I achieve this? I want to use this BaseBriefViewModel for a lot of Select2 in the project. So hard coding a static error message is not a good idea. What I really want to do is pass a error message from parent object. Like Branch is required in this specific case. Maybe in some other class I might pass Product is required
Any direction will be appreciated
At the moment this is not supported - but support is in planned. See dotnet github issue:
https://github.com/dotnet/runtime/issues/36093

Polymorphic model binding / Complex Models

I have problem in model binding. When I submit form it returns me id=0 and device is null? and how to solve it. My goal is to add new device, and choose device type from view by selector. if user selects smartphone it has to add fields for smartphone. I don't want to save device type in base class as Kind variable. Thanks in advance(sorry for english)
controller->
public IActionResult Index()
{
MainCont mainCont = new MainCont();
return View(mainCont);
}
index.cshtml ->
#model MainCont
#{
ViewData["Title"] = "Home Page";
}
<form action="home/create" method="post">
#Html.Partial("example",Model.Device)
<button type="submit">გაგზავნა</button>
</form>
example.cshtml ->
#model SmartPhone
#Html.TextBoxFor(model => model.imei)
#Html.TextBoxFor(model => model.screensize)
Device Model ->
public abstract class Device : Object
{
}
LaptopModel ->
public class Laptop : Device
{
public string CPU { get; set; }
public string GPu { get; set; }
}
MainCont ->
public class MainCont
{
public int Id{ get; set; }
public Device Device { get; set; }
}
SmartphoneModel ->
public class SmartPhone : Device
{
public string screensize { get; set; }
public string imei { get; set; }
}
model binder ->
using Bind.Models;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Bind
{
public class DeviceModelBinder : IModelBinder
{
private Dictionary<Type, (ModelMetadata, IModelBinder)> binders;
public DeviceModelBinder(Dictionary<Type, (ModelMetadata, IModelBinder)> binders)
{
this.binders = binders;
}
public async Task BindModelAsync(ModelBindingContext bindingContext)
{
IModelBinder modelBinder;
ModelMetadata modelMetadata;
if (bindingContext.ModelType == typeof(Laptop))
{
(modelMetadata, modelBinder) = binders[typeof(Laptop)];
}
else if (bindingContext.ModelType == typeof(SmartPhone))
{
(modelMetadata, modelBinder) = binders[typeof(SmartPhone)];
}
else
{
bindingContext.Result = ModelBindingResult.Failed();
return;
}
var newBindingContext = DefaultModelBindingContext.CreateBindingContext(
bindingContext.ActionContext,
bindingContext.ValueProvider,
modelMetadata,
bindingInfo: null,
bindingContext.ModelName);
await modelBinder.BindModelAsync(newBindingContext);
bindingContext.Result = newBindingContext.Result;
if (newBindingContext.Result.IsModelSet)
{
// Setting the ValidationState ensures properties on derived types are correctly
bindingContext.ValidationState[newBindingContext.Result] = new ValidationStateEntry
{
Metadata = modelMetadata,
};
}
}
}
}
binderprovider ->
using Bind.Models;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Bind
{
public class DeviceModelBinderProvider: IModelBinderProvider
{
public IModelBinder GetBinder(ModelBinderProviderContext context)
{
if (context.Metadata.ModelType != typeof(Device))
{
return null;
}
var subclasses = new[] { typeof(Laptop), typeof(SmartPhone), };
var binders = new Dictionary<Type, (ModelMetadata, IModelBinder)>();
foreach (var type in subclasses)
{
var modelMetadata = context.MetadataProvider.GetMetadataForType(type);
binders[type] = (modelMetadata, context.CreateBinder(modelMetadata));
}
return new DeviceModelBinder(binders);
}
}
}
Here is a demo:
Index.cshtml(when select SmartPhone,use example.cshtml,when select Laptop,use example1.cshtml):
#model MainCont
#{
ViewData["Title"] = "Home Page";
}
<form asp-action="create" asp-controller="home" method="post">
<select id="select" name="select">
<option value="SmartPhone">SmartPhone </option>
<option value="Laptop">Laptop </option>
</select>
<div id="sample"></div>
<button type="submit">გაგზავნა</button>
</form>
#section scripts{
<script>
$(function () {
GetPartialView();
})
$("#select").change(function () {
GetPartialView();
})
function GetPartialView() {
$.ajax({
url: "/Test1/ReturnExample",
type: "POST",
data: {
select: $("#select").val()
},
success: function (data) {
$('#sample').html(data);
},
error: function (reponse) {
alert("error : " + reponse);
}
});
}
</script>
}
example.cshtml:
#model SmartPhone
#Html.TextBoxFor(model => model.imei)
#Html.TextBoxFor(model => model.screensize)
example1.cshtml:
#model Laptop
#Html.TextBoxFor(model => model.CPU)
#Html.TextBoxFor(model => model.GPu)
Controller:
public IActionResult Index()
{
return View(new MainCont());
}
public IActionResult ReturnExample(string select)
{
if (select == "SmartPhone")
{
return PartialView("~/Views/Test1/example.cshtml", new SmartPhone());
}
else {
return PartialView("~/Views/Test1/example1.cshtml", new Laptop());
}
}
Create Action in Home Controller:
[HttpPost]
public IActionResult Create([ModelBinder(typeof(DataBinder))]MainCont mainCont) {
return Ok();
}
DataBinder:
public class DataBinder : IModelBinder
{
public Task BindModelAsync(ModelBindingContext bindingContext)
{
if (bindingContext == null)
{
throw new ArgumentNullException(nameof(bindingContext));
}
var model1 = new MainCont();
var select = bindingContext.ValueProvider.GetValue("select").FirstValue;
if (select == "SmartPhone")
{
var model2 = new SmartPhone();
model2.screensize = bindingContext.ValueProvider.GetValue("screensize").FirstValue;
model2.imei = bindingContext.ValueProvider.GetValue("imei").FirstValue;
model1.Device = model2;
}
else if (select == "Laptop")
{
var model2 = new Laptop();
model2.CPU = bindingContext.ValueProvider.GetValue("CPU").FirstValue;
model2.GPu = bindingContext.ValueProvider.GetValue("GPu").FirstValue;
model1.Device = model2;
}
bindingContext.Result = ModelBindingResult.Success(model1);
return Task.CompletedTask;
}
}
result:

How to populate google charts using SQL Server Database in MVC Razor

I wish to replace the hard coded data with SQL Server Database.
However, I'm stucked as I am still new to this.. I just tried the Google Chart and its working with hard-coded values, please guide me step-by-step to change the values to data from my database.
If theres any informations you need, please let me know. I'll try to provide them. Thanks for the help in advance guys! ):
Code for my Model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ChartInMvcApplication.Models
{
public class ProductModel
{
public string YearTitle { get; set; }
public string SaleTitle { get; set; }
public string PurchaseTitle { get; set; }
public Product ProductData { get; set; }
}
public class Product
{
public string Year { get; set; }
public string Purchase { get; set; }
public string Sale { get; set; }
}
}
Code for my Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ChartInMvcApplication.Models;
namespace ChartInMvcApplication.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
ProductModel objProductModel = new ProductModel();
objProductModel.ProductData = new Product();
objProductModel.ProductData = GetChartData();
objProductModel.YearTitle = "Year";
objProductModel.SaleTitle = "Sale";
objProductModel.PurchaseTitle = "Purchase";
return View(objProductModel);
}
/// <summary>
/// Code to get the data which we will pass to chart
/// </summary>
/// <returns></returns>
public Product GetChartData()
{
Product objproduct = new Product();
/*Get the data from databse and prepare the chart record data in string form.*/
objproduct.Year = "2009,2010,2011,2012,2013,2014";
objproduct.Sale = "2000,1000,3000,1500,2300,500";
objproduct.Purchase = "2100,1400,2900,2400,2300,1500";
return objproduct;
}
}
}
Code for my View:
#model ChartInMvcApplication.Models.ProductModel
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
// Create and populate the data table.
var years = [#Model.ProductData.Year];
var sales = [#Model.ProductData.Sale];
var Purchase = [#Model.ProductData.Purchase];
var data = new google.visualization.DataTable();
data.addColumn('string', '#Model.YearTitle');
data.addColumn('number', '#Model.SaleTitle');
data.addColumn('number', '#Model.PurchaseTitle');
for (i = 0; i < years.length; i++) {
data.addRow([years[i].toString(), sales[i], Purchase[i]]);
}
var options = {
title: 'Sale and Purchase Compare',
hAxis: { title: '#Model.YearTitle', titleTextStyle: { color: 'red'} }
};
var chart = newgoogle.visualization.ColumnChart(document.getElementById('chartdiv'));
chart.draw(data, options);
}
</script>
<div id="chartdiv" style="width: 500px; height: 300px;">
</div>
You have to add data to each product object.
public Product GetChartData()
{
Product objproduct = new Product();
//Get Data for years as a string list.
List<string> years = Database.GetYears();
foreach(var year in years)
GetChartDataForYear(year, ref objproduct);
return objproduct;
}
public void GetChartDataForYear(string year, Product objproduct out)
{
if(!string.IsNullorEmpty(objproduct.Year))
objproduct.Year += (",");
if(!string.IsNullorEmpty(objproduct.Sale))
objproduct.Sale += (",");
if(!string.IsNullorEmpty(objproduct.Purchase ))
objproduct.Purchase += (",");
objproduct.Year += year.ToString();
objproduct.Sale += GetSale(int year);
objproduct.Purchase += GetPurchase(int year);
}
public string GetSale(string year)
{
// To get from DB.
return "";
}
public string GetPurchase(string year)
{
// To get from DB.
return "";
}
The best way is to bring the values from the database and bind them into a list, then do a foreach to populate your chart.
In your model create 3 functions like this :
public List<string> getYears()
{
List<string> years = new List<string>();
string connectionString = ConfigurationManager.AppSettings["StringConnection"].ToString();
using (SqlConnection cn = new SqlConnection(connectionString))
{
cn.Open();
SqlCommand sqlCommand = new SqlCommand("SELECT year FROM tableTest", cn);
SqlDataReader reader = sqlCommand.ExecuteReader();
while (reader.Read())
{
years.Add(reader["year"].ToString());
}
cn.Close();
}
return years;
}
public List<string> getSale()
{
List<string> sales = new List<string>();
List<string> years = getYears();
foreach (var year in years)
{
string connectionString = ConfigurationManager.AppSettings["StringConnection"].ToString();
using (SqlConnection cn = new SqlConnection(connectionString))
{
cn.Open();
SqlCommand sqlCommand = new SqlCommand("SELECT sale FROM tableTest where year = '" + year + "'", cn);
SqlDataReader reader = sqlCommand.ExecuteReader();
while (reader.Read())
{
sales.Add(reader["sale"].ToString());
}
cn.Close();
}
}
return sales;
}
public List<string> getPurchase()
{
List<string> purchases = new List<string>();
List<string> years = getYears();
foreach (var year in years)
{
string connectionString = ConfigurationManager.AppSettings["StringConnection"].ToString();
using (SqlConnection cn = new SqlConnection(connectionString))
{
cn.Open();
SqlCommand sqlCommand = new SqlCommand("SELECT purchase FROM tableTest where year = '" + year + "'", cn);
SqlDataReader reader = sqlCommand.ExecuteReader();
while (reader.Read())
{
purchases.Add(reader["purchase"].ToString());
}
cn.Close();
}
}
return purchases;
}
Add a function in your Model to change Lists to strings:
public string listToString(List<string> list)
{
string output = "";
foreach(var item in list)
{
output = (String.IsNullOrEmpty(output)) ? item : output + "," + item;
}
return output;
}
In your controller the function will be :
public Product GetChartData()
{
ProductModel prod = new ProductModel();
Product objproduct = new Product();
/*Get the data from databse and prepare the chart record data in string form.*/
objproduct.Year = prod.listToString(prod.getYears());
objproduct.Sale = prod.listToString(prod.getSale());
objproduct.Purchase = prod.listToString(prod.getPurchase());
return objproduct;
}

Not Get data in jstree

I am create menu of Category and SubCategory in my project using jstree.
but i do not get or not show my data in jstree format.
so, what is problem.?
Plz Help me.
thnks....
My Controller Code
[HttpGet]
public JsonResult GetCatList()
{
IEnumerable<Category> cats = _CategoryBusiness.Select();
return new JsonResult
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = cats
};
}
My Model Class
[Serializable]
public class Category
{
[Key]
[DisplayName("Id")]
public int CategoryID { get; set; }
public string CategoryName { get; set; }
public int? SubCategoryID { get; set; }
[ForeignKey("SubCategoryID")]
public virtual Category SubCategory { get; set; }
}
And _CategoryBusiness.Select() is
public List<Category> Select(int id = 0)
{
var selectFrom = _Ctx.Categories.Select(a => a);
var query = selectFrom.Select(a => a);
if(id > 0)
query = query.Where(a => a.CategoryID == id);
return query.ToList();
}
And My View Page code is
<script type="text/javascript">
$(function () {
FillJSTree();
});
function FillJSTree() {
$("#onflycheckboxes").jstree({
json_data: {
"ajax": {
"url": "/Categories/GetCatList/",
"type": "GET",
"dataType": "json",
"contentType": "application/json charset=utf-8",
}
},
//checkbox: {
// real_checkboxes: true,
// checked_parent_open: true
//},
plugins: ["themes", "json_data", "ui"]
});
}
</script>
.
.
.
.
..
<div id="onflycheckboxes">
</div>
Try this: Before sending data to view, serialize that. This works for me. P.s. Your category data must be tree node.
[HttpGet]
public string GetCatList()
{
IEnumerable<Category> cats = _CategoryBusiness.Select();
string myjsonmodel = new JavaScriptSerializer().Serialize(cats);
return myjsonmodel;
}

MVC populate drop down list no postback

Is their a way to populate a drop down list by pressing a button without post back.
Ex: dropdownlist1 -> a
press button
and populates dropdownlist2 with different data regarding dropdownlist1 value.
Thanks
Most common scenario is generating the second dropdownlist values depending on the first DropDownList selected item changed. I assume that you are looking for the same scenario and below code is for achieve that. Let me know if you really need the button click to generate the second dropdown.
Model:
namespace MvcApplicationrazor.Models
{
public class CountryModel
{
public List<State> StateModel { get; set; }
public SelectList FilteredCity { get; set; }
}
public class State
{
public int Id { get; set; }
public string StateName { get; set; }
}
public class City
{
public int Id { get; set; }
public int StateId { get; set; }
public string CityName { get; set; }
}
}
Controller:
public ActionResult Index()
{
CountryModel objcountrymodel = new CountryModel();
objcountrymodel.StateModel = new List<State>();
objcountrymodel.StateModel = GetAllState();
return View(objcountrymodel);
}
//Action result for ajax call
[HttpPost]
public ActionResult GetCityByStaeId(int stateid)
{
List<City> objcity = new List<City>();
objcity = GetAllCity().Where(m => m.StateId == stateid).ToList();
SelectList obgcity = new SelectList(objcity, "Id", "CityName", 0);
return Json(obgcity);
}
// Collection for state
public List<State> GetAllState()
{
List<State> objstate = new List<State>();
objstate.Add(new State { Id = 0, StateName = "Select State" });
objstate.Add(new State { Id = 1, StateName = "State 1" });
objstate.Add(new State { Id = 2, StateName = "State 2" });
objstate.Add(new State { Id = 3, StateName = "State 3" });
objstate.Add(new State { Id = 4, StateName = "State 4" });
return objstate;
}
//collection for city
public List<City> GetAllCity()
{
List<City> objcity = new List<City>();
objcity.Add(new City { Id = 1, StateId = 1, CityName = "City1-1" });
objcity.Add(new City { Id = 2, StateId = 2, CityName = "City2-1" });
objcity.Add(new City { Id = 3, StateId = 4, CityName = "City4-1" });
objcity.Add(new City { Id = 4, StateId = 1, CityName = "City1-2" });
objcity.Add(new City { Id = 5, StateId = 1, CityName = "City1-3" });
objcity.Add(new City { Id = 6, StateId = 4, CityName = "City4-2" });
return objcity;
}
View:
#model MvcApplicationrazor.Models.CountryModel
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script language="javascript" type="text/javascript">
function GetCity(_stateId) {
var procemessage = "<option value='0'> Please wait...</option>";
$("#ddlcity").html(procemessage).show();
var url = "/Test/GetCityByStaeId/";
$.ajax({
url: url,
data: { stateid: _stateId },
cache: false,
type: "POST",
success: function (data) {
var markup = "<option value='0'>Select City</option>";
for (var x = 0; x < data.length; x++) {
markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
}
$("#ddlcity").html(markup).show();
},
error: function (reponse) {
alert("error : " + reponse);
}
});
}
</script>
<h4>
MVC Cascading Dropdown List Using Jquery</h4>
#using (Html.BeginForm())
{
#Html.DropDownListFor(m => m.StateModel, new SelectList(Model.StateModel, "Id", "StateName"), new { #id = "ddlstate", #style = "width:200px;", #onchange = "javascript:GetCity(this.value);" })
<br />
<br />
<select id="ddlcity" name="ddlcity" style="width: 200px">
</select>
<br /><br />
}

Resources