Display data in Dropdown using model with List<selectListItem> - asp.net-mvc

I'm new to MVC and would like to bind data in DropDownList using Model. But I'm not sure how to get into that.
Below is my code
--Model
public string Name { get; set; }
public string Qualification { get; set; }
public string CountryID { get; set; }
public string StateID { get; set; }
public string CityID { get; set; }
public List<SelectList> CountryList { get; set; }
//public List<SelectListItem> Country { get; set; }
public List<SelectList> StateList { get; set; }
public List<SelectList> CityList { get; set; }
--View
<tr>
<td>#Html.LabelFor(s => s.Name)</td>
<td>#Html.TextBoxFor(s => s.Name, new { #class = "form-control" })</td>
</tr>
<tr>
<td>#Html.LabelFor(s => s.Qualification)</td>
<td>#Html.TextBoxFor(s => s.Qualification, new { #class = "form-control" })</td>
</tr>
<tr>
<td>#Html.LabelFor(s => s.Country)</td>
<td>#Html.DropDownList("Country", new SelectList(Model.CountryList), "Select Country", new { #Class = "form-control" })</td>
</tr>
--Controller
public ActionResult DisplayView(EmployeeDetails.Models.DisplayModel dm)
{
EmployeeDetails.Models.DisplayModel obj = new EmployeeDetails.Models.DisplayModel();
List<SelectListItem> CountryList = obj.CountryDetails(dm);
//var CountryList = obj.CountryDetails(dm);
obj.CountryList = new SelectList(CountryList, "Value", "Text");
return View();
}
In model, I have a method(CountryDetails) to return COuntrylist as List from Database.
I'm getting error in the below line to assign values to the list in model.
obj.CountryList = new SelectList(CountryList, "Value", "Text");
Please help me out to display the value correctly in Dropdown.

I have just replicated you issue and made some changes to make it run.
In Model i have made change from list<SelectList> to List<SelectListItem>
after that i have PopulateCountry dropdownlist hardcoded data in controller which you can change it by replacing it with database.
After populating dropdownlist next using jquery ajax i have populated states and city dropdownlist.
Model
public class DisplayModel
{
[Display(Name = "Choose Country")]
public string Country { get; set; }
public string Name { get; set; }
public string Qualification { get; set; }
public string CountryID { get; set; }
public string StateID { get; set; }
public string CityID { get; set; }
public List<SelectListItem> CountryList { get; set; }
public List<SelectListItem> StateList { get; set; }
public List<SelectListItem> CityList { get; set; }
}
Controller Code
public class DemoController : Controller
{
// GET: Demo
public ActionResult Index()
{
DisplayModel obj = new DisplayModel();
obj.CountryList = PopulateCountry();
return View(obj);
}
private static List<SelectListItem> PopulateCountry()
{
List<SelectListItem> li = new List<SelectListItem>();
li.Add(new SelectListItem { Text = "Select", Value = "0" });
li.Add(new SelectListItem { Text = "India", Value = "1" });
li.Add(new SelectListItem { Text = "Srilanka", Value = "2" });
return li;
}
public JsonResult GetStates(string id)
{
List<SelectListItem> states = new List<SelectListItem>();
switch (id)
{
case "1":
states.Add(new SelectListItem { Text = "Select", Value = "0" });
states.Add(new SelectListItem { Text = "ANDAMAN & NIKOBAR ISLANDS", Value = "1" });
states.Add(new SelectListItem { Text = "MAHARASHTRA", Value = "2" });
break;
}
return Json(new SelectList(states, "Value", "Text"));
}
public JsonResult GetCity(string id)
{
List<SelectListItem> City = new List<SelectListItem>();
switch (id)
{
case "2":
City.Add(new SelectListItem { Text = "Select", Value = "0" });
City.Add(new SelectListItem { Text = "MUMBAI", Value = "1" });
City.Add(new SelectListItem { Text = "PUNE", Value = "2" });
City.Add(new SelectListItem { Text = "KOLHAPUR", Value = "3" });
City.Add(new SelectListItem { Text = "RATNAGIRI", Value = "4" });
City.Add(new SelectListItem { Text = "NAGPUR", Value = "5" });
City.Add(new SelectListItem { Text = "JALGAON", Value = "6" });
break;
}
return Json(new SelectList(City, "Value", "Text"));
}
}
View
#model WebApplication1.Models.DisplayModel
#{
ViewBag.Title = "Index";
}
<table>
<tr>
<td>#Html.LabelFor(s => s.Country)</td>
<td>#Html.DropDownList("Country", Model.CountryList, "Select Country", new { #Class = "form-control" })</td>
</tr>
<tr>
<td>State</td>
<td>#Html.DropDownList("State", new SelectList(string.Empty, "Value", "Text"), "Please select a State", new { style = "width:250px", #class = "form-control" }) </td>
</tr>
<tr>
<td>City</td>
<td>#Html.DropDownList("city", new SelectList(string.Empty, "Value", "Text"), "Please select a city", new { style = "width:250px", #class = "form-control" }) </td>
</tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
//Dropdownlist Selectedchange event
$("#Country").change(function () {
$("#State").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("GetStates")', // we are calling json method
dataType: 'json',
data: { id: $("#Country").val() },
// here we are get value of selected country and passing same valueas inputto json method GetStates.
success: function (states) {
// states contains the JSON formatted list
// of states passed from the controller
$.each(states, function (i, state) {
$("#State").append('<option value="' + state.Value + '">' + state.Text + '</option>');
// here we are adding option for States
});
},
error: function (ex) {
alert('Failed to retrieve states.' + ex);
}
});
return false;
})
});
</script>
<script type="text/javascript">
$(document).ready(function () {
//Dropdownlist Selectedchange event
$("#State").change(function () {
$("#city").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("GetCity")',
dataType: 'json',
data: { id: $("#State").val() },
success: function (citys) {
// states contains the JSON formatted list
// of states passed from the controller
$.each(citys, function (i, city) {
$("#city").append('<option value="' + city.Value + '">' + city.Text + '</option>');
});
},
error: function (ex) {
alert('Failed to retrieve states.' + ex);
}
});
return false;
})
});
</script>

Related

How do I to get id of an enum value with #DropDownListFor?

I created an Enum and the values has id now I need to get the id in #Html.DropDownListFor but I don't know how to do it.
How could I get the id of Enum ?
Enum
public enum GainLosses
{
Gain = 1,
Loss = 2
};
Model
//Gain/Loss
[DisplayName("Gain/Loss")]
public int gainLoss { get; set; }
public IEnumerable<SelectListItem> gainLosses
{
get { return CustomEnum.Enum.GetItems<GainLosses>().Select(x => new SelectListItem() { Text = x.ToString(), Value = x.ToString() }); }
}
//
HTML
<div class="form-group">
<label for="#Html.IdFor(model => model.gainLoss)" class="cols-sm-2 control-label">Gain/Loss <img src="~/Imagens/required.png" height="6" width="6" title="requerido"></label>
#Html.DropDownListFor(model => model.gainLoss, Model.gainLosses, new { Class = "form-control" })
#Html.ValidationMessageFor(model => model.gainLoss, "", new { #class = "text-danger" })
</div><!--/Gain/Loss-->
I've already solved the problem.
[DisplayName("Gain/Loss")]
public int gainLoss { get; set; }
public IEnumerable<SelectListItem> gainLosses
{
get { return CustomEnum.Enum.GetItems<GainLosses>().Select(x => new SelectListItem() { Text = x.ToString(), Value = ((int)x).ToString() }); }
}
//

ASP.Net MVC: Selected country id value in dropdown not passing to controller

i have webgrid where i am showing student data like ID, name and student country. all data is in editable format. country data appear in dropdown.
my UI
here is my controller code
public class WebGridMoreControlsController : Controller
{
// GET: WebGridMoreControls
public ActionResult Index()
{
StudentListViewModel osvm = new StudentListViewModel();
return View(osvm);
}
[HttpPost]
public ActionResult Index(StudentListViewModel oStudentListViewModel)
{
return View(oStudentListViewModel);
}
}
here is my model code
public class Student
{
public int ID { get; set; }
public string Name { get; set; }
public int CountryID { get; set; }
}
public class Country
{
public int ID { get; set; }
public string Name { get; set; }
}
viewmodel code
public class StudentListViewModel
{
public IList<Student> Students { get; set; }
public int SelectedCountryId { set; get; }
public List<Country> Country { get; set; }
public StudentListViewModel()
{
Students = new List<Student>
{
new Student{ID=1,Name="Keith",CountryID=1},
new Student{ID=2,Name="Paul",CountryID=2},
new Student{ID=3,Name="Sam",CountryID=3}
};
Country = new List<Country>
{
new Country{ID=1,Name="India"},
new Country{ID=2,Name="UK"},
new Country{ID=3,Name="USA"}
};
}
}
here is my razor view code
#model MVCCRUDPageList.Models.StudentListViewModel
#{
ViewBag.Title = "Index";
}
<h2>Student View Model</h2>
#using (Html.BeginForm("Index", "WebGridMoreControls", FormMethod.Post))
{
var grid = new WebGrid(Model.Students, canSort: false, canPage: false);
var rowNum = 0;
<div id="gridContent" style=" padding:20px; ">
#grid.GetHtml(
tableStyle: "table",
alternatingRowStyle: "alternate",
selectedRowStyle: "selected",
headerStyle: "header",
columns: grid.Columns
(
grid.Column(null, null, format: item => rowNum = rowNum + 1),
grid.Column("ID", format: (item) => #Html.TextBoxFor(m => m.Students[rowNum - 1].ID, new { #class = "edit-mode" })),
grid.Column("Name", format: (item) => #Html.TextBoxFor(m => m.Students[rowNum - 1].Name, new { #class = "edit-mode" })),
grid.Column("Country", format: (item) =>
#Html.DropDownListFor(x => x.SelectedCountryId,
new SelectList(Model.Country, "ID", "Name", Model.SelectedCountryId = item.CountryID),
"-- Select States--", new { id = "cboCountry", #class = "edit-mode" }))
))
<input type="submit" value="Submit" />
</div>
}
where did i made the mistake for which changed country ID from drowdown not getting pass to action when i submit form. country id is also 0.
Your Student model contains a property CountryID which is the property you need to bind to. Remove the public int SelectedCountryId { set; get; } property from your view model, and change the code in the view to bind to CountryID
grid.Column("Country", format: (item) =>
#Html.DropDownListFor(
x => x.Students[rowNum - 1].CountryID,
new SelectList(Model.Country, "ID", "Name", item.CountryID),
"-- Select States--",
new { #class = "edit-mode" }
)
)
In addition, remove the new { id = "cboCountry" } from the DropDownListFor() method which is generating invalid html (duplicate id attributes)
Note you current code binds the value of the selected option in each <select> to your SelectedCountryId property, but the DefaultModelBinder only binds the first value in the request, so the value of SelectedCountryId would be the value of the selected option in the first row (i.e. the ID associated with 'India' in your image).

ASP.Net MVC: How to force user to select any checkbox by data annotation

i have showing many checkboxes for hobbies property in view model but i like to attach ValidationMessageFor as a result user should be force to select any one checkbox out of many.
so here is model & viewmodel
public class Hobby
{
public string Name { get; set; }
public bool IsSelected { get; set; }
}
public class SampleViewModel
{
[Required(ErrorMessage = "Select any Hobbies")]
public List<Hobby> Hobbies { get; set; }
}
action method code
public ActionResult Index()
{
var SampleVM = new SampleViewModel();
SampleVM.Products = new List<Product>
{
new Product{ ID=1, Name="IPhone" },
new Product{ ID=2, Name="MacBook Pro" },
new Product{ ID=3, Name="iPod" }
};
SampleVM.Hobbies = new List<Hobby>()
{
new Hobby(){ Name = "Reading", IsSelected= false },
new Hobby(){ Name = "Sports" ,IsSelected= false},
new Hobby(){ Name = "Movies" ,IsSelected= false}
};
return View(SampleVM);
}
[HttpPost]
public ActionResult Index(SampleViewModel vm)
{
ViewBag.IsPostBack = false;
if (ModelState.IsValid)
{
Product p = vm.Products.Where(x => x.ID == vm.SelectedProductId).FirstOrDefault();
ViewBag.IsPostBack = true;
ViewBag.ProductID = p.ID.ToString();
ViewBag.ProductName = p.Name.ToString();
return View(vm);
}
else
{
var SampleVM = new SampleViewModel();
SampleVM.Products = new List<Product>
{
new Product{ ID=1, Name="IPhone" },
new Product{ ID=2, Name="MacBook Pro" },
new Product{ ID=3, Name="iPod" }
};
SampleVM.Hobbies = new List<Hobby>()
{
new Hobby(){ Name = "Reading", IsSelected= false },
new Hobby(){ Name = "Sports" ,IsSelected= true},
new Hobby(){ Name = "Movies" ,IsSelected= true}
};
return View(SampleVM);
}
view code
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<b>Hobbies</b><br />
#for (int x = 0; x < Model.Hobbies.Count(); x++)
{
#Html.CheckBoxFor(p => p.Hobbies[x].IsSelected) #:
#Html.LabelFor(p => p.Hobbies[x].IsSelected, Model.Hobbies[x].Name) #:
}
</div>
#Html.ValidationMessageFor(model => model.Hobbies, "", new { #class = "text-danger" })
</div>
so tell me what to change in code as a result validation message will fire if user select no check boxes for hobbies.
thanks

ASP.NET MVC : How to bind dropdown list with nested list type property

here is my full code. who will see it then they could understand what i am trying to achieve. after seeing my code if anyone think there is problem in code design then please discuss with rectified version.
view model and model code
public class MainViewModel
{
public List<Student> Students { get; set; }
public int SelectedState = 0;
public int SelectedCity = 0;
}
public class Student
{
public int ID = 0;
public string Name = "";
public int StateID = 0;
public int CityID = 0;
public List<States> States { get; set; }
public List<Cities> Cities { get; set; }
}
public class States
{
public int ID = 0;
public string Name = "";
}
public class Cities
{
public int ID = 0;
public string Name = "";
}
Controller code from where i am populating my view model and model
public ActionResult Index()
{
MainViewModel oVm = new MainViewModel()
{
Students = new List<Student>() {
new Student
{
ID=1,
Name="JoyDev",
StateID=1,
CityID=1,
States=new List<States>()
{
new States
{
ID=1,
Name="WestBengal",
},
new States
{
ID=2,
Name="Bihar",
},
new States
{
ID=3,
Name="Orrisa",
}
},
Cities=new List<Cities>()
{
new Cities
{
ID=1,
Name="Alipur"
},
new Cities
{
ID=2,
Name="Asansol"
},
new Cities
{
ID=3,
Name="Andul"
}
}
},
//***********
new Student
{
ID=1,
Name="Mukti",
StateID=2,
CityID=1,
States=new List<States>()
{
new States
{
ID=1,
Name="WestBengal",
},
new States
{
ID=2,
Name="Bihar",
},
new States
{
ID=3,
Name="Orrisa",
}
},
Cities=new List<Cities>()
{
new Cities
{
ID=1,
Name="Janpur"
},
new Cities
{
ID=2,
Name="Madhubani"
},
new Cities
{
ID=3,
Name="Kanti"
}
}
},
//***********
new Student
{
ID=1,
Name="Somnath",
StateID=3,
CityID=2,
States=new List<States>()
{
new States
{
ID=1,
Name="WestBengal",
},
new States
{
ID=2,
Name="Bihar",
},
new States
{
ID=3,
Name="Orrisa",
}
},
Cities=new List<Cities>()
{
new Cities
{
ID=1,
Name="Chandapur"
},
new Cities
{
ID=2,
Name="Dhankauda"
},
new Cities
{
ID=3,
Name="Konarak"
}
}
}
}
};
return View();
}
view code where i was trying to bind drop down.
#model WebApplication1.Models.MainViewModel
#{
ViewBag.Title = "Home Page";
}
<div>
<table>
<tr>
<td>ID</td>
<td>Name</td>
<td>State</td>
<td>City</td>
</tr>
#foreach (var m in Model.Students)
{
<tr>
<td><input type="text" value="#m.ID" /></td>
<td><input type="text" value="#m.Name" /></td>
<td>
#Html.DropDownList("CityID", new SelectList(ViewData["CityList"] as List<SelectListItem>, "Value", "Text", m.CityID))
#Html.DropDownListFor(x => x.SelectedState new SelectList(Model.Students.States, "ID", "Name", Model.SelectedState), "-- Select States--", new { id = "cboState", #class = "edit-mode" })
</td>
<td>
#Html.DropDownListFor(x => x.SelectedCity new SelectList(Model.Students.Cities, "ID", "Name", Model.SelectedCity), "-- Select States--", new { id = "cboState", #class = "edit-mode" })
</td>
</tr>
}
</table>
</div>
main problem lies here
#Html.DropDownListFor(x => x.SelectedState new SelectList(Model.Students.States, "ID", "Name", Model.SelectedState), "-- Select States--", new { id = "cboState", #class = "edit-mode" })
main question is how to bind drop down with nested list type property Model.Students.States.
thanks
My issue has been solved. so i like to give my updated code because the same code may help other.
my viewmodel and model classes
public class MainViewModel
{
public List<Student> Students { get; set; }
public int SelectedState = 0;
public int SelectedCity = 0;
}
public class Student
{
public int ID = 0;
public string Name = "";
public int StateID = 0;
public int CityID = 0;
public List<States> States { get; set; }
public List<Cities> Cities { get; set; }
}
public class States
{
public int ID { get; set; }
public string Name { get; set; }
}
public class Cities
{
public int ID { get; set; }
public string Name { get; set; }
}
Controller from where i populate my model
public class HomeController : Controller
{
public ActionResult Index()
{
MainViewModel oVm = new MainViewModel()
{
Students = new List<Student>() {
new Student
{
ID=1,
Name="JoyDev",
StateID=1,
CityID=1,
States=new List<States>()
{
new States
{
ID=1,
Name="WestBengal",
},
new States
{
ID=2,
Name="Bihar",
},
new States
{
ID=3,
Name="Orrisa",
}
},
Cities=new List<Cities>()
{
new Cities
{
ID=1,
Name="Alipur"
},
new Cities
{
ID=2,
Name="Asansol"
},
new Cities
{
ID=3,
Name="Andul"
}
}
},
//***********
new Student
{
ID=1,
Name="Mukti",
StateID=2,
CityID=1,
States=new List<States>()
{
new States
{
ID=1,
Name="WestBengal",
},
new States
{
ID=2,
Name="Bihar",
},
new States
{
ID=3,
Name="Orrisa",
}
},
Cities=new List<Cities>()
{
new Cities
{
ID=1,
Name="Janpur"
},
new Cities
{
ID=2,
Name="Madhubani"
},
new Cities
{
ID=3,
Name="Kanti"
}
}
},
//***********
new Student
{
ID=1,
Name="Somnath",
StateID=3,
CityID=2,
States=new List<States>()
{
new States
{
ID=1,
Name="WestBengal",
},
new States
{
ID=2,
Name="Bihar",
},
new States
{
ID=3,
Name="Orrisa",
}
},
Cities=new List<Cities>()
{
new Cities
{
ID=1,
Name="Chandapur"
},
new Cities
{
ID=2,
Name="Dhankauda"
},
new Cities
{
ID=3,
Name="Konarak"
}
}
}
}
};
return View(oVm);
}
}
view code
#model BuildTable.Models.MainViewModel
#{
ViewBag.Title = "Home Page";
}
<div>
<table>
<tr>
<td>ID</td>
<td>Name</td>
<td>State</td>
<td>City</td>
</tr>
#for(int i = 0; i < Model.Students.Count; i++)
{
<tr>
<td><input type="text" value="#Model.Students[i].ID" /></td>
<td><input type="text" value="#Model.Students[i].Name" /></td>
<td>
#Html.DropDownListFor(m => m.Students[i].StateID, new SelectList(Model.Students[i].States, "ID", "Name",Model.Students[i].StateID), "-- Select States--", new { #class = "edit-mode" })
</td>
<td>
#Html.DropDownListFor(m => m.Students[i].CityID, new SelectList(Model.Students[i].Cities, "ID", "Name",Model.Students[i].CityID), "-- Select Cities--", new { #class = "edit-mode" })
</td>
</tr>
}
</table>
</div>
thanks
Models:
namespace MyProject.Models
{
public class ViewInfo
{
public int StateID { get; set; }
public int? CityID { get; set; }
}
public class Student
{
public int ID { get; set; }
public string FullName { get; set; }
public int CityID { get; set; }
}
public class State
{
public int ID { get; set; }
public string Name { get; set; }
}
public Class City
{
public int ID { get; set; }
public int StateID { get; set; }
public string Name { get; set; }
}
}
Controllers:
using MyProject.Models;
namespace MyProject.Controllers
{
public class StudentsController : Controller
{
private MyDBEntities _context;
public StudentsController()
{
this._context = new MyDBEntities();
}
// StudentsController
public ActionResult Index()
{
ViewBag.ViewInfo = new ViewInfo { StateID = 1 };
ViewBag.StateID = _context.States.Select(s => new SelectListItem { Value = s.ID, Text = s.Name }).ToList();
return View(_context.Students.ToList());
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(ViewInfo viewInfo)
{
ModelState.Clear();
ViewBag.ViewInfo = viewInfo;
ViewBag.StateID = _context.States.Select(s => new SelectListItem { Value = s.ID, Text = s.Name, Selected = s.ID == viewInfo.StateID }).ToList();
ViewBag.CityID = _context.Cities.Select(s => new SelectListItem { Value = s.ID, Text = s.Name, Selected = s.ID == viewInfo.CityID ?? 1 }).ToList();
var viewModel = _context.Students.Where(s => s.Cities.StateID == viewInfo.StateID && (viewInfo.CityID == null || s.CityID == viewInfo.CityID)).ToList();
return View(viewModel);
}
}
}
And the View:
#using MyProject.Models;
#model IEnumerable<MyProject.Models.Student>
#{
ViewBag.Title = "Students";
ViewInfo viewInfo = ViewBag.ViewInfo;
}
<div class="page-header">
<h2>Students</h2>
</div>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken();
#Html.DropDownList("StateID", null, new { #class = "form-control" })
if(viewInfo.CityID != null){ #Html.DropDownList("CityID", null, new { #class = "form-control" }) }
<input type="submit" value="Filter" class="btn btn-primary" />
// Students Table
}

I want to fill city dropdown automatically from database according to state dropdown in ASP.NET MVC and Ajax

I want to get city list from database and store selected city's id into database. I have used Ajax to call function of member class. But it is not working, please help me to sort this out.
Here is my Model:
[Required]
[Display(Name = "State")]
public int stateid { get; set; }
public string stateName { get; set; }
public List<SelectListItem> stateList = new List<SelectListItem>();
[Required]
[Display(Name = "City")]
public int Cityid { get; set; }
public string CityName { get; set; }
public List<SelectListItem> CityList = new List<SelectListItem>();
clubDataContext cd = new clubDataContext();
public void insertmember(M_Reg m)
{
M_Registarion m1 = new M_Registarion();
m1.M_StatteId = m.stateid;
m1.M_CityId = 1; //temporary storing 1
cd.M_Registarions.InsertOnSubmit(m1);
cd.SubmitChanges();
}
Here is my controller:
[HttpGet]
public ActionResult Registration()
{
var model = new M_Reg();
using (var db = new clubDataContext())
{
model.stateList = content2.Select(c2 => new SelectListItem
{
Text = c2.S_Name,
Value = c2.S_ID.ToString()
}).ToList();
}
return View(model);
}
[HttpGet]
public SelectList getCity(int stateId, int selectCityId)
{
var db = new clubDataContext();
var model = new M_Reg();
var content = from p in db.CityInfos where p.S_ID == stateId
select new { p.C_ID, p.C_Name };
model.CityList = content.Select(c => new SelectListItem
{
Text = c.C_Name,
Value = c.C_ID.ToString()
}).ToList();
return new SelectList(model.CityList, "Value", "Text", selectCityId);
}
View:
Razor code:
<div class="editor-label">
#Html.LabelFor(m=> m.stateid)
</div>
<div class="editor-field">
#Html.DropDownListFor(m => m.stateid,Model.stateList)
#Html.ValidationMessageFor(m => m.stateid)
</div>
<div class="editor-label">
#Html.LabelFor(m=> m.Cityid)
</div>
<div class="editor-field">
#Html.DropDownListFor(m => m.Cityid, Model.CityList)
#Html.ValidationMessageFor(m => m.Cityid, Model.c)
</div>
Ajax code:
$("#stateid").change(function () {
$.ajax({
type: "POST",
url: '#Url.Action("Member", "getCity")',
data: { stateId: $("#stateid > option:selected").attr("value") },
success: function (data) {
var items = [];
items.push("<option>--Choose Your City--</option>");
$.each(data, function () {
items.push("<option value=" + this.Value + ">" + this.Text + "</option>");
});
$("#Cityid").html(items.join(' '));
}
})
});
Try Like This
Here Controller :
public JsonResult functionname(){
List<string> City = new List<string>();
var DBcity = yourDBentity.TableName.Where(x=>x.columnname==condition).select(x=>x.city);
foreach(var i in DBcity){
City.Add(i);
}
return Json(City, JsonRequestBehavior.AllowGet);
}
Jquery:
$(document).ready(function (result) {
$.post('/yourcontorller/functionname', {parameter : parameter }, function (result) {
$.each(result, function (key, value) {
$('#yourDropdownId').append($("<option></option>").html(value).val(value));
});
},"json");
});
Finally, this code works...
Model Class:
clubDataContext _db = new clubDataContext();
[Required]
[Display(Name="City")]
public virtual string icityid { get; set; }
public List<SelectListItem> cityList = new List<SelectListItem>();
[Required]
[Display(Name = "State")]
public virtual string istateid { get; set; }
public SelectList getState()
{
IEnumerable<SelectListItem> stateList = (from m in _db.StateInfos select m).AsEnumerable().Select(m => new SelectListItem() { Text = m.S_Name, Value = m.S_ID.ToString() });
return new SelectList(stateList, "Value", "Text", istateid);
}
View :
<div class="editor-label">
#Html.LabelFor(m=> m.istateid)
</div>
<div class="editor-field">
#Html.DropDownListFor(m => m.istateid,Model.getState(),"--Choose your State--")
#Html.ValidationMessageFor(m => m.istateid)
</div>
<div class="editor-label">
#Html.LabelFor(m=> m.icityid)
</div>
<div class="editor-field">
#Html.DropDownListFor(m => m.icityid,Model.cityList,"--Choose your City--")
#Html.ValidationMessageFor(m => m.icityid)
</div>
Ajax:
$('#istateid').change(function(){
$.ajax({
type:"POST",
url:'#Url.Action("getCityJson","Member")',
data: { stateId : $("#istateid > option:selected").attr("value")},
success: function (data){
var items= [];
$.each(data,function(){
items.push("<option value=" + this.Value + ">" + this.Text + "</option>");
});
$("#icityid").html(items.join(' '));
}
})
});
And Controller:
[HttpPost]
public JsonResult getCityJson(string stateId, string selectCityId=null)
{
return Json(getCity(stateId, selectCityId));
}
public SelectList getCity(string stateId, string selectCityId = null)
{
var db = new clubDataContext();
IEnumerable<SelectListItem> cityList = new List<SelectListItem>();
if (!string.IsNullOrEmpty(stateId))
{
int _stateId = Convert.ToInt32(stateId);
cityList = (from m in db.CityInfos where m.S_ID == _stateId select m).AsEnumerable().Select(m => new SelectListItem() { Text = m.C_Name, Value = m.C_ID.ToString() });
}
return new SelectList(cityList, "Value", "Text", selectCityId);
}

Resources