Dropdown list with population with where clause - asp.net-mvc

I want to populate the second dropdown list GetCity() with values from a Data Base that are dependent on whatever was selected in the the first list or GetCounty() dropdown. Where would i add the where clause?
public class NewsModel : BaseModel
{
[Required]
public int? FKCountyId { get; set; }
public string County { get; set; }
[Required]
public int? FKCityId { get; set; }
public string City { get; set; }
public List<SelectListItem> GetCounty()
{
List<SelectListItem> lst = new List<SelectListItem>();
lst.Add(new SelectListItem() { Text = "Please select County", Value = "" });
foreach (var item in LambertonContext.NewsCounties)
{
lst.Add(new SelectListItem() { Text = item.County, Value = item.PKCountyId.ToString() });
}
return lst;
}
public List<SelectListItem> GetCity()
{
List<SelectListItem> lst = new List<SelectListItem>();
lst.Add(new SelectListItem() { Text = "Please select City", Value = "" });
foreach (var item in LambertonContext.NewsCities)
{
lst.Add(new SelectListItem() { Text = item.City, Value = item.PKCityId.ToString() });
}
return lst;
}
}
<div class="panel-body">
<div class="form-group">
#Html.LabelFor(m => m.FKCountyId, new { #class = "col-sm-2 col-sm-2 control-label" })
<div class="col-sm-10">
#Html.DropDownListFor(m => m.FKCountyId, Model.GetCounty())
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.FKCityId, new { #class = "col-sm-2 col-sm-2 control-label" })
<div class="col-sm-10">
#Html.DropDownListFor(m => m.FKCityId, Model.GetCity())
</div>
</div>

You will need to pass the CountyId to your GetCity() and filter your list;
try this:
public List<SelectListItem> GetCity(string CountyId)
{
List<SelectListItem> lst = new List<SelectListItem>();
lst.Add(new SelectListItem() { Text = "Please select City", Value = "" });
foreach (var item in LambertonContext.NewsCities.Where(FKCountyId == GetCounty().Value))
{
lst.Add(new SelectListItem() { Text = item.City, Value = item.PKCityId.ToString() });
}
return lst;
}

Related

How to store and display SelectList data

I am using SelectList to populate dropdownlists in my view. It works for the Create and Edit views to store ID value data in a table. How do I retrieve the 'Name' value to display in a Details view?
Model
Public Class Employee {
[Key]
public int ID { get; set;}
public string UserName {get; set; }
public byte Gender { get; set; }
}
ViewModel
public class EmployeeEditViewModel {
public int ID { get; set; }
public string UserName { get; set; }
public SelectList GenderList { get; set; }
public EmployeeEditViewModel () {
GenderList = CommonHelper.GenderList(null);
}
}
Helper
public static SelectList GenderList(object selected)
{
return new SelectList(new[]
{
new { Value = 0, Name = "Male" },
new { Value = 1, Name = "Female" }
}
, "Value", "Name", selected);
}
Edit View
#model Models.ViewModel.EmployeeEditViewModel
#using (Html.BeginForm()) {
#Html.HiddenFor(model => model.ID)
<div class="form-group">
#Html.LabelFor(model => model.UserName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.UserName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.UserName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.GenderList, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.Gender, Model.GenderList, "- Select -", new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.GenderList, "", new { #class = "text-danger" })
</div>
</div>
}
Controller
[HttpPost]
public ActionResult CreateEmployee(EmployeeEditViewModel emProfile)
{
try
{
if (ModelState.IsValid)
{
Employee newUser = new Employee();
newUser.UserName = emProfile.UserName;
newUser.Gender = emProfile.Gender;
userRepository.Add(newUser);
userRepository.SaveChanges();
return RedirectToAction("Index");
}
}
catch (Exception ex)
{ }
return View(emProfile);
}
So far it works great, I am able to create, edit Employee records and 1 or 0 is stored in the table for the gender.
But when I want to display the employee data in a details view how do I get the text 'Male' or 'Female'?
I ended up creating a helper method to retrieve the text.
public static string GetTextFromSelectList(int id, string listName)
{
string selectedText = string.Empty;
SelectListItem selectedItem;
switch (listName)
{
case "Gender":
selectedItem = Helper.CommonHelper.GenderList(null).FirstOrDefault(x => x.Value == id.ToString());
selectedText = selectedItem == null ? null : selectedItem.Text;
break;
default:
selectedText = null;
break;
}
return selectedText;
}

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() }); }
}
//

Selected Option in dropdownlisfor not work

I have this model
public string Rol { get; set; }
[Display(Name = "Perfil:")]
[Required(ErrorMessage = "Seleccione un perfil para el usuario")]
public static IEnumerable<SelectListItem> Roles
{
get
{
yield return new SelectListItem { Text = "Administrador", Value = "1" };
yield return new SelectListItem { Text = "Consultor", Value = "2" };
}
}
public int IdProject { get; set; }
public string ProjectDesc { get; set; }
my controller:
public ActionResult _Update(string user, string name, string rol)
{
var obj = new AdministracionDto
{
User = user,
Name = name,
Rol = "2"
};
// ViewBag.Roles1 = new SelectList(AdministracionDto.Roles, "Id", "Name");
return PartialView("_Update", obj);
}
the partial view is a Pop Up, where the user click on link "Actualizar" of the view. and shows the popup
#using (Html.BeginForm("Update", "Login", FormMethod.Post, new { style = "register", style = "height: 34px;" } ))
{
<b>#Html.LabelFor(model => model.Name)</b>
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { PlaceHolder = "Ingrese nombre", #required = "required", #class = "input-register", style = "height: 34px;" } })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
<b>#Html.LabelFor(model => model.Rol)</b>
#Html.DropDownListFor(m => m.Rol, AdministracionDto.Roles, "--Seleccione Perfil", new { #class = "form-control", #required = "required" })
#Html.ValidationMessageFor(model => model.Rol, "", new { #class = "text-danger" })
<button type="button"class="close" data-dismiss="modal">Cancelar</button>
<button type="submit" class="signupbtn" value="Create">Actualizar</button>
}
but my problem is: that when goes to the actionresult _Update. I lose the selected value in the dropdownlisFor . but I need establish the value in "2.

Issue extending the base EDMX model and calling the functions in the data model

I am writing a solution using MVC with scaffolding. It uses Entity Framework v6 and is database first in design. The base data model (ServiceAccountFilter) is extended by the data model (FilterModel). There is some logic in the FilterModel but the properties are all inherited from the base model. It seems as though the controller insists on using the base model. When I change the return to use the FilterModel, I get an error that the view requires the base model and then the functions in the FilterModel are not visible in the views? Not sure how to handle this?
Base Model:
namespace FHN.ARX.AdminWeb
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
public partial class ServiceAccountFilter
{
[DisplayName("Filter ID")]
public virtual int FilterId { get; set; }
[DisplayName("Filter Name")]
public virtual string FilterName { get; set; }
[DisplayName("Service Account")]
public virtual string ServiceAccount { get; set; }
[DisplayName("Doc Type")]
public virtual string DocType { get; set; }
[DisplayName("Doc Type ID")]
public virtual Nullable<int> DocTypeId { get; set; }
[DisplayName("Doc Name ID")]
public virtual string DocNameId { get; set; }
[DisplayName("Last Modified By ID")]
public virtual string LastModifiedById { get; set; }
[DisplayName("Last Modified By")]
public virtual string LastModifiedByName { get; set; }
[DisplayName("Last Modified")]
public virtual Nullable<System.DateTime> LastModified { get; set; }
[DisplayName("Months To Return")]
public virtual Nullable<int> MonthsToReturn { get; set; }
}
}
FilterModel
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace FHN.ARX.AdminWeb.Models
{
public class FilterModel : ServiceAccountFilter
{
[DisplayName("Filter ID")]
public override int FilterId { get; set; }
[DisplayName("Filter Name")]
public override string FilterName { get; set; }
[DisplayName("Service Account")]
public override string ServiceAccount { get; set; }
[DisplayName("Doc Type")]
public override string DocType { get; set; }
[DisplayName("Doc Type ID")]
public override Nullable<int> DocTypeId { get; set; }
[DisplayName("Doc Name ID")]
public override string DocNameId { get; set; }
[DisplayName("Last Modified By ID")]
public override string LastModifiedById { get; set; }
[DisplayName("Last Modified By")]
public override string LastModifiedByName { get; set; }
[DisplayName("Last Modified")]
public override Nullable<System.DateTime> LastModified { get; set; }
[DisplayName("Months To Return")]
public override Nullable<int> MonthsToReturn { get; set; }
public bool Selected { get; set; }
public string Checkboxes { get; set; }
public IEnumerable<SelectListItem> DocTypesList(string id)
{
using (var db = new ARXEntities())
{
var docType = new List<SelectListItem>();
docType = (from t in db.vwMapDocNamesToSecurityUsers
where t.UserDN == id
orderby t.DocType
select new { t.DocType, t.DocTypeId }).Distinct().Select(x => new SelectListItem() { Text = x.DocType, Value = x.DocTypeId.ToString() }).OrderBy(x => x.Text).ToList();
return docType;
}
}
public IEnumerable<SelectListItem> DocNamesList()
{
using (var db = new ARXEntities())
{
IEnumerable<SelectListItem> docName = new List<SelectListItem>();
var loggedInUser = "C2693"; // HttpContext.Current.User.Identity.Name.Split('\\')[1];
docName = (from t in db.vwMapDocNamesToSecurityUsers
where t.UserDN == loggedInUser
select new { t.DocName, t.DocNameId, t.DocTypeId }).Distinct().Select(x => new SelectListItem()
{
Text = x.DocName,
Value = x.DocNameId.ToString(),
Group = new SelectListGroup() { Name = x.DocTypeId.ToString() }
}).Distinct().OrderBy(x => x.Text).ToList();
var docCount = docName.Count();
return docName;
}
}
public IEnumerable<SelectListItem> ServiceAccountList()
{
using (var db = new ARXEntities())
{
var sa = new List<SelectListItem>();
sa = (from t in db.vwMapDocNamesToSecurityUsers
where t.UserDN.StartsWith("sa_")
orderby t.UserDN
select new { t.UserDN }).Distinct().Select(x => new SelectListItem() { Text = x.UserDN, Value = x.UserDN }).OrderBy(x => x.Text).ToList();
return sa;
}
}
public IEnumerable<SelectListItem> DocNamesByDocTypeIdList()
{
using (var db = new ARXEntities())
{
IEnumerable<SelectListItem> docName = new List<SelectListItem>();
docName = (from t in db.vwMapDocNamesToSecurityUsers
select new { t.DocName, t.DocNameId, t.DocTypeId }).Distinct().Select(x => new SelectListItem()
{
Text = x.DocName,
Value = x.DocNameId.ToString(),
Group = new SelectListGroup() { Name = x.DocTypeId.ToString() }
}).Distinct().OrderBy(x => x.Text).ToList();
var docCount = docName.Count();
return docName;
}
}
public IEnumerable<SelectListItem> GetDocNamesForFilterId(int? id)
{
using (var db = new ARXEntities())
{
IEnumerable<SelectListItem> docName = new List<SelectListItem>();
docName = (from t in db.ServiceAccountFilters
where t.FilterId == id
select new { t.DocNameId, t.FilterId }).Distinct().Select(x => new SelectListItem()
{
Text = x.DocNameId,
Value = x.DocNameId.ToString(),
Group = new SelectListGroup() { Name = x.DocNameId.ToString() }
}).Distinct().OrderBy(x => x.Text).ToList();
return docName;
}
}
}
}
Controller Edit Action
public ActionResult Edit(int? id)
{
if (id == null)
{
var saf = new FilterModel();
return View(saf);
}
FilterModel serviceAccountFilter = (FilterModel)db.ServiceAccountFilters.Find(id); <----Tried casting here, but still didnt work.
if (serviceAccountFilter == null)
{
return HttpNotFound();
}
return View(serviceAccountFilter);
}
Edit View
#model FHN.ARX.AdminWeb.Models.FilterModel
#{
ViewBag.Title = "Edit A Filter";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="pageTitle">Filter Maintenance</div>
#using (Html.BeginForm(new { id = "filterForm" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.FilterId)
#Html.HiddenFor(model => model.LastModified)
#Html.HiddenFor(model => model.LastModifiedById)
#Html.HiddenFor(model => model.LastModifiedByName)
<div class="ddlGroups, btmMarg-15">
#Html.DropDownListFor(m => m.ServiceAccount, Model.ServiceAccountList(), "Select a Service Account")
</div>
<div class="ddlGroups, col-md-10, btmMarg-15">
#Html.LabelFor(model => model.ServiceAccount, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.EditorFor(model => model.ServiceAccount, new { htmlAttributes = new { #class = "form-control" } })
</div>
<div class="ddlGroups, col-md-10, btmMarg-15">
#Html.LabelFor(model => model.DocTypeId, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.EditorFor(model => model.DocTypeId, new { htmlAttributes = new { #class = "form-control" } })
</div>
<p class="leftMarg-15 text-default" id="docNamesHdrText">Select the document names to be included in the filter.</p>
<div class="ckDocNames">
#foreach (var dn in Model.DocNamesByDocTypeIdList())
{
<div class="checkboxContainer">
<input class="ckBoxes" type="checkbox" name="DocNameId" value="#dn.Value" dtid="#dn.Group.Name" />#dn.Text<br />
</div>
}
</div>
<div class="form-group, col-md-10, btmMarg-15" id="monthsGroup">
#Html.LabelFor(model => model.MonthsToReturn, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.EditorFor(model => model.MonthsToReturn, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.MonthsToReturn, "", new { #class = "text-danger" })
</div>
<div class="form-group, col-md-10, btmMarg-15" id="filterNameGroup">
#Html.LabelFor(model => model.FilterName, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.EditorFor(model => model.FilterName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FilterName, "", new { #class = "text-danger" })
</div>
<br />
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" id="modSaveButton" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "ActiveFilters") |
#Html.ActionLink("Admin Home", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
this is an example of using a viewmodel on your case ... (may be it's not prefect but just a hint on your way)
namespace FHN.ARX.AdminWeb
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
public partial class ServiceAccountFilter
{
public int FilterId { get; set; }
public string FilterName { get; set; }
public string ServiceAccount { get; set; }
public string DocType { get; set; }
public Nullable<int> DocTypeId { get; set; }
public string DocNameId { get; set; }
public string LastModifiedById { get; set; }
public string LastModifiedByName { get; set; }
public Nullable<System.DateTime> LastModified { get; set; }
public Nullable<int> MonthsToReturn { get; set; }
}
}
no need for the filter model now and instead of that put all the logic in the controller under a heper region
#region Helpers
public IEnumerable<SelectListItem> DocTypesList(string id)
{
using (var db = new ARXEntities())
{
var docType = new List<SelectListItem>();
docType = (from t in db.vwMapDocNamesToSecurityUsers
where t.UserDN == id
orderby t.DocType
select new { t.DocType, t.DocTypeId }).Distinct().Select(x => new SelectListItem() { Text = x.DocType, Value = x.DocTypeId.ToString() }).OrderBy(x => x.Text).ToList();
return docType;
}
}
public IEnumerable<SelectListItem> DocNamesList()
{
using (var db = new ARXEntities())
{
IEnumerable<SelectListItem> docName = new List<SelectListItem>();
var loggedInUser = "C2693"; // HttpContext.Current.User.Identity.Name.Split('\\')[1];
docName = (from t in db.vwMapDocNamesToSecurityUsers
where t.UserDN == loggedInUser
select new { t.DocName, t.DocNameId, t.DocTypeId }).Distinct().Select(x => new SelectListItem()
{
Text = x.DocName,
Value = x.DocNameId.ToString(),
Group = new SelectListGroup() { Name = x.DocTypeId.ToString() }
}).Distinct().OrderBy(x => x.Text).ToList();
var docCount = docName.Count();
return docName;
}
}
public IEnumerable<SelectListItem> ServiceAccountList()
{
using (var db = new ARXEntities())
{
var sa = new List<SelectListItem>();
sa = (from t in db.vwMapDocNamesToSecurityUsers
where t.UserDN.StartsWith("sa_")
orderby t.UserDN
select new { t.UserDN }).Distinct().Select(x => new SelectListItem() { Text = x.UserDN, Value = x.UserDN }).OrderBy(x => x.Text).ToList();
return sa;
}
}
public IEnumerable<SelectListItem> DocNamesByDocTypeIdList()
{
using (var db = new ARXEntities())
{
IEnumerable<SelectListItem> docName = new List<SelectListItem>();
docName = (from t in db.vwMapDocNamesToSecurityUsers
select new { t.DocName, t.DocNameId, t.DocTypeId }).Distinct().Select(x => new SelectListItem()
{
Text = x.DocName,
Value = x.DocNameId.ToString(),
Group = new SelectListGroup() { Name = x.DocTypeId.ToString() }
}).Distinct().OrderBy(x => x.Text).ToList();
var docCount = docName.Count();
return docName;
}
}
public IEnumerable<SelectListItem> GetDocNamesForFilterId(int? id)
{
using (var db = new ARXEntities())
{
IEnumerable<SelectListItem> docName = new List<SelectListItem>();
docName = (from t in db.ServiceAccountFilters
where t.FilterId == id
select new { t.DocNameId, t.FilterId }).Distinct().Select(x => new SelectListItem()
{
Text = x.DocNameId,
Value = x.DocNameId.ToString(),
Group = new SelectListGroup() { Name = x.DocNameId.ToString() }
}).Distinct().OrderBy(x => x.Text).ToList();
return docName;
}
}
#endregion
in your controller Edit Action
public ActionResult Edit(int? id)
{
if (id == null)
{
var saf = new FilterModel();
return View(saf);
}
var serviceAccountFilter = db.ServiceAccountFilters.Find(id)
if (serviceAccountFilter == null)
{
return HttpNotFound();
}
var model = new FilterViewModel
{
FilterId = serviceAccountFilter.FilterId,
FilterName = serviceAccountFilter.FilterName,
ServiceAccount = serviceAccountFilter.ServiceAccount,
DocType = serviceAccountFilter.DocType,
DocTypeId = serviceAccountFilter.DocTypeId,
DocNameId = serviceAccountFilter.DocNameId,
LastModifiedById = serviceAccountFilter.LastModifiedById,
LastModifiedByName = serviceAccountFilter.LastModifiedByName,
LastModified = serviceAccountFilter.LastModified,
MonthsToReturn = serviceAccountFilter.MonthsToReturn,
ServiceAccountList = ServiceAccountList(),
DocNamesByDocTypeIdList = DocNamesByDocTypeIdList()
};
return View(model);
}
and here is a ViewModel lets say it's name will be FilterViewModel
public class FilterModel
{
[DisplayName("Filter ID")]
public int FilterId { get; set; }
[DisplayName("Filter Name")]
public string FilterName { get; set; }
[DisplayName("Service Account")]
public string ServiceAccount { get; set; }
[DisplayName("Doc Type")]
public string DocType { get; set; }
[DisplayName("Doc Type ID")]
public Nullable<int> DocTypeId { get; set; }
[DisplayName("Doc Name ID")]
public string DocNameId { get; set; }
[DisplayName("Last Modified By ID")]
public string LastModifiedById { get; set; }
[DisplayName("Last Modified By")]
public string LastModifiedByName { get; set; }
[DisplayName("Last Modified")]
public Nullable<System.DateTime> LastModified { get; set; }
[DisplayName("Months To Return")]
public Nullable<int> MonthsToReturn { get; set; }
public IEnumerable<SelectListItem> ServiceAccountList { get; set; }
public IEnumerable<SelectListItem> DocNamesByDocTypeIdList { get; set; }
}
and then your Edit View will be
#model FilterViewModel // check the name space
#{
ViewBag.Title = "Edit A Filter";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="pageTitle">Filter Maintenance</div>
#using (Html.BeginForm(new { id = "filterForm" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.FilterId)
#Html.HiddenFor(model => model.LastModified)
#Html.HiddenFor(model => model.LastModifiedById)
#Html.HiddenFor(model => model.LastModifiedByName)
<div class="ddlGroups, btmMarg-15">
#Html.DropDownListFor(m => m.ServiceAccount, Model.ServiceAccountList(), "Select a Service Account")
</div>
<div class="ddlGroups, col-md-10, btmMarg-15">
#Html.LabelFor(model => model.ServiceAccount, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.EditorFor(model => model.ServiceAccount, new { htmlAttributes = new { #class = "form-control" } })
</div>
<div class="ddlGroups, col-md-10, btmMarg-15">
#Html.LabelFor(model => model.DocTypeId, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.EditorFor(model => model.DocTypeId, new { htmlAttributes = new { #class = "form-control" } })
</div>
<p class="leftMarg-15 text-default" id="docNamesHdrText">Select the document names to be included in the filter.</p>
<div class="ckDocNames">
#foreach (var dn in Model.DocNamesByDocTypeIdList())
{
<div class="checkboxContainer">
<input class="ckBoxes" type="checkbox" name="DocNameId" value="#dn.Value" dtid="#dn.Group.Name" />#dn.Text<br />
</div>
}
</div>
<div class="form-group, col-md-10, btmMarg-15" id="monthsGroup">
#Html.LabelFor(model => model.MonthsToReturn, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.EditorFor(model => model.MonthsToReturn, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.MonthsToReturn, "", new { #class = "text-danger" })
</div>
<div class="form-group, col-md-10, btmMarg-15" id="filterNameGroup">
#Html.LabelFor(model => model.FilterName, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.EditorFor(model => model.FilterName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FilterName, "", new { #class = "text-danger" })
</div>
<br />
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" id="modSaveButton" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "ActiveFilters") |
#Html.ActionLink("Admin Home", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}

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