DropdownList is giving a null value to controller calling model - c#

I am a student developer in ASP.NET. I have a question which i did not find a solution about it. I can build a form for my controller. i am taking a value from my input objects but i am not taking value from dropdown list to my controller. It gives null value on my controller. Could you help me about where i made a mistake?
My View Model :
public class CountryViewModel
{
public IEnumerable<Country> CountryList { get; set; }
public Country Country;
}
My controller :
public ActionResult Index()
{
var model = new CountryViewModel()
{
CountryList = db.Country.ToList()
};
return View(model);
}
[HttpPost]
public ActionResult Index(string timeForCheckedOut,CountryViewModel cvModel)
{
return View();
}
my index.cshtml:
#model PenaltyCalculation.Models.ViewModel.CountryViewModel
<form class="" style="margin-top:10%;" action="/" method="post">
<div class="form-group">
<label>Check out date of the Book</label>
<input class="form-control" type="date" name="timeForCheckedOut">
</div>
<div class="form-group">
<label>Choose a country</label>
#Html.DropDownListFor(m=>m.Country.countryId,new SelectList(Model.CountryList,"countryId","countryName"),new {#class="form-control" })
</div>
<button type="submit" class="btn btn-primary">Calculate</button>
</form>
My Country Model:
public partial class Country
{
public int countryId { get; set; }
public string countryName { get; set; }
}

Option #1:
You just need to put the { get; set; } on the end of Country in your CountryViewModel. This will allow you to set the countryId value, but the name will not be set. You will have to look that up from your db if you need that also.
public class CountryViewModel
{
public IEnumerable<Country> CountryList { get; set; }
public Country Country { get; set; }
}
Option #2
This is what I would do. Remake your CountryViewModel to actually represent your View's Model.
public class CountryViewModel
{
public int CountryID { get; set; }
public DateTime TimeForCheckedOut { get; set; }
}
Then update your controller.
// Simulating a db
private List<Country> Countries;
public HomeController()
{
// Initializing sample data
Countries = new List<Country>();
Countries.Add(new Country() { countryId = 1, countryName = "USA" });
Countries.Add(new Country() { countryId = 2, countryName = "England" });
Countries.Add(new Country() { countryId = 3, countryName = "Japan" });
Countries.Add(new Country() { countryId = 4, countryName = "China" });
}
public ActionResult Index()
{
// I prefer using the ViewData Dictionary for my selectlists
ViewData["CountrySelectList"] = new SelectList(Countries, "countryId", "countryName");
return View();
}
[HttpPost]
public ActionResult Index(CountryViewModel cvModel)
{
var country = Countries.First(c => c.countryId == cvModel.CountryId);
// Do Stuff Like Saving and Updating
ViewData["CountrySelectList"] = new SelectList(Countries, "countryId", "countryName", cvModel.CountryId);
return View(cvModel);
}
And Finally update your View
#model PenaltyCalculation.Models.ViewModel.CountryViewModel
<form class="" style="margin-top:10%;" action="/" method="post">
<div class="form-group">
<label>Check out date of the Book</label>
<input class="form-control" type="date" name="timeForCheckedOut">
</div>
<div class="form-group">
<label>Choose a country</label>
#Html.DropDownListFor(m => m.CountryId, (SelectList)ViewBag.CountrySelectList, new { #class = "form-control" })
</div>
<button type="submit" class="btn btn-primary">Calculate</button>
</form>

public class CountryController : Controller
{
// GET: Country
public ActionResult Index()
{
var model = new CountryViewModel()
{
CountryList = GetCountries()
};
return View(model);
}
[HttpPost]
public ActionResult Index(CountryViewModel model)
{
model.CountryList = GetCountries();
return View(model);
}
private IEnumerable<Country> GetCountries()
{
return new Country[]
{
new Country()
{
CountryID = 1,
CountryName = "USA"
},
new Country()
{
CountryID = 2,
CountryName = "Mexico"
},
};
}
}
public class CountryViewModel
{
public IEnumerable<Country> CountryList { get; set; }
public int CountryID { get; set; }
public DateTime? TimeForCheckedOut { get; set; }
}
public partial class Country
{
public int CountryID { get; set; }
public string CountryName { get; set; }
}
<form class="" style="margin-top:10%;" action="/Country/Index" method="post">
<div class="form-group">
<label>Check out date of the Book</label>
<input class="form-control" type="date" name="TimeForCheckedOut">
</div>
<div class="form-group">
<label>Choose a country</label>
#Html.DropDownListFor(m => m.CountryID, new SelectList(Model.CountryList, "CountryID", "CountryName"), new { #class = "form-control" })
</div>
<button type="submit" class="btn btn-primary">Calculate</button>
</form>
This is working for me
Make sure CountryID has getter and setter. Also in C# public property name starts with Capital letter (by convention)
I would also suggest, don't bind Country entity directly to view. You may want to create CountryModel

Related

Partial view data doesn't get saved in ASP.NET Core MVC

I create class Project in project class I define technology and another i define Class Technology I seed data in technology and after that i create dropdown list in Project Create view using a partial view and when I save data the technology can not be saved
public class Project
{
public int ProjectId { get; set; }
[StringLength(60, MinimumLength = 3)]
public string? ProjectName { get; set; }
public string? Description { get; set; }
public DateTime Start { get; set; }
public DateTime? End { get; set; }
public string? ProjectHead { get; set; }
public string? Status { get; set; }
public string? Technology { get; set; }
}
public class Technology
{
public int TechnologyId { get; set; }
public string? TechnologyName { get; set; }
}
This is my controller:
public async Task<IActionResult> Create([Bind("ProjectId,ProjectName,Description,Start,End,ProjectHead,Status,Technology")] Project project)
{
if (ModelState.IsValid)
{
_context.Add(project);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(project);
}
This is my view of project create:
<div class="row">
<partial name="_Technologypartial" />
</div>
technology Patial
#model TeamManagement.Models.Technology
<div class="row">
<div class="form-group col-md-6">
<label>Technology</label>
<br />
<select asp-for="TechnologyId" class="form-control" asp-items="#(new SelectList(ViewBag.Technology,"TechnologyId","TechnologyName"))">
</select>
</div>
</div>
EDIT
View
<div class="row">
<partial name="_Technologypartial" model="#Model.technology" />
</div>
Controller
{
var list = _context.Technology.ToList();
List<SelectListItem> dropdown = new List<SelectListItem>();
foreach (var item in list)
{
dropdown.Add(new SelectListItem()
{
Text = item.TechnologyName,
Value = item.TechnologyId.ToString()
});
}
PartialViewData model = new PartialViewData();
ViewBag.Technology = dropdown;
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(PartialViewData model)
{
if (ModelState.IsValid)
{
Project project = new Project()
{
ProjectId = model.project.ProjectId,
ProjectName = model.project.ProjectName,
Description = model.project.Description,
Start = model.project.Start,
End = model.project.End,
ProjectHead = model.project.ProjectHead,
Status = model.project.Status,
Technology = model.technology.TechnologyId.ToString()
};
_context.Add(project);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(model);
}
When you select an option in Partial View, After submiting the form, You want save the value of option. I suggest you to use ViewModel to achieve it. Refer to this simple demo:
I simplified your class for testing convenience.
public class Project
{
public string Name { get; set; }
public string? Technology { get; set; }
}
public class Technology
{
public int TechnologyId { get; set; }
public string? TechnologyName { get; set; }
}
Create a View model to pass the value.
public class PartialViewData
{
public PartialViewData()
{
project = new Project();
technology = new Technology();
}
public Project project { get; set; }
public Technology technology { get; set; }
}
DbContext
public class MvcMovieContext : DbContext
{
public MvcMovieContext(DbContextOptions<MvcMovieContext> options) : base(options)
{
}
public DbSet<Technology> technology { get; set; }
}
Controller
public class HomeController : Controller
{
private readonly MvcMovieContext _context;
public HomeController(MvcMovieContext context)
{
_context = context;
}
public IActionResult Index()
{
return View();
}
public IActionResult Privacy()
{
var list = _context.technology.ToList();
List<SelectListItem> dropdown = new List<SelectListItem>();
foreach(var item in list)
{
dropdown.Add(new SelectListItem()
{
Text = item.TechnologyName,
Value = item.TechnologyId.ToString()
}) ;
}
PartialViewData model = new PartialViewData();
ViewBag.Technology = dropdown;
return View(model);
}
[HttpPost]
public IActionResult Privacy(PartialViewData model)
{
Project project = new Project()
{
Name = model.project.Name,
Technology = model.technology.TechnologyId.ToString()
};
//......
return View();
}
}
View
#model PartialViewData
<form method="post">
<input asp-for="#Model.project.Name" />
<div class="row">
<partial name="_Technologypartial" model="#Model.technology" />
</div>
<button type="submit">submit</button>
</form>
_Technologypartial
#model Technology
<div class="row">
<div class="form-group col-md-6">
<label>Technology</label>
<br />
<select name="technology.TechnologyId" class="form-control" asp-items=#ViewBag.Technology>
</select>
</div>
</div>
Demo:
Edit=================
public IActionResult Create()
{
var list = _context.technology.ToList();
List<SelectListItem> dropdown = new List<SelectListItem>();
foreach(var item in list)
{
dropdown.Add(new SelectListItem()
{
Text = item.TechnologyName,
Value = item.TechnologyId.ToString()
}) ;
}
PartialViewData model = new PartialViewData();
ViewBag.Technology = dropdown;
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(PartialViewData model)
{
if (ModelState.IsValid)
{
//change here
var name = _context.Technology.Where(x => x.TechnologyId == model.technology.TechnologyId).Select(x => x.TechnologyName).FirstOrDefault();
Project project = new Project()
{
ProjectId = model.project.ProjectId,
ProjectName = model.project.ProjectName,
Description = model.project.Description,
Start = model.project.Start,
End = model.project.End,
ProjectHead = model.project.ProjectHead,
Status = model.project.Status,
//change here
Technology = name
};
_context.Add(project);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(model);
}
View
#model PartialViewData
<div class="row">
<partial name="_Technologypartial" model="#Model.technology" />
</div>
_Technologypartial
#model Technology
<div class="row">
<div class="form-group col-md-6">
<label>Technology</label>
<br />
<select name="technology.TechnologyId" class="form-control" asp-items=#ViewBag.Technology>
</select>
</div>
</div>

Unable to add the value from dropdownlist to database

I created a form to store information about the customers and his membership type. For that I am using the drop down list to hold values for membership types. But on submitting the form, the value(Id) for membership type isnt added to database
//Model Membership Types
public int Id { get; set; }
public string Name { get; set; }
//ViewModel NewCustomerviewModel
public IEnumerable<MembershipTypes> MembershipTypes { get; set; }
public Customers Customers{ get; set; }
//Controler CustomerController
public IActionResult Index()
{
var customers = _context.Customers.Include(c => c.MembershipTypes).ToList();
return View(customers);
}
[HttpPost]// Create is the aciton for Submit Button
public IActionResult Create(Customers customers)
{
_context.Customers.Add(customers);
_context.SaveChanges();
return RedirectToAction("Index", "Customers");
}
//View Model
#model Wes.ViewModels.NewCustomerviewModel;
#Html.DropDownListFor(m => m.Customers.MembershipTypes, new SelectList(Model.MembershipTypes, "Id", "Name"),"Select Membership Type", new { #class = "form-control" })
When the Form is Submitted, it should add all the values to the database including the value of Drop Down List Membership Types
You could try doing it this way:
//model
public int Id { get; set; }
public string Name { get; set; }
public enum MembershipTypes
{
Type1,
Type2,
Type3
}
public MembershipTypes _membershipTypes {get; set; }
//controller
[HttpPost]
public IActionResult Create([Bind("Id","Name","_membershipTypes")] Customers customers)
{
if (ModelState.IsValid)
{
_context.Add(customers);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
Return View(customers);
}
//view
<div class="row">
<div class="col-md-6">
<form asp-action="Create">
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
#Html.DropDownList("_membershipTypes",
new SelectList(Enum.GetValues(typeof(MembershipTypes))),
"Select membership type",
new { #class = "form-control" })
</div>
<input type="submit" value="Submit!" />
</form>
</div>
</div>
You need to show more about the relationships(one-to-one,one-to-many) of your models.
The parameters of your post action need to correspond with the model of your view,use NewCustomerviewModel instead of Customers.
The dropdownlist shows the type of name and pass id as value to action, so your asp-for of dropdown list needs to be set for an id or id list.
Refer to my demo which pass id list of MembershipTypes to action using multiple select.
1.My ViewModel NewCustomerviewModel,
public class MembershipTypes
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
}
public class NewCustomerviewModel
{
public int[] SelectMembershipTypesId { get; set; }
public Customers Customers { get; set; }
}
public class Customers
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public IEnumerable<MembershipTypes> MembershipTypes { get; set; }
}
2.Create GET action
public IActionResult Create()
{
var model = new NewCustomerviewModel()
{
Customers = new Customers()
{
MembershipTypes = _context.MembershipTypes.ToList()
},
};
return View(model);
}
3.Create POST action
[HttpPost]
public async Task<IActionResult> Create(NewCustomerviewModel viewmodel)
{
if (ModelState.IsValid)
{
viewmodel.Customers.MembershipTypes= _context.MembershipTypes
.Where(m =>viewmodel.SelectMembershipTypesId.Contains(m.Id))
.ToList();
_context.Add(viewmodel.Customers);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(viewmodel);
}
4. Create View
#Html.DropDownListFor(m => m.SelectMembershipTypesId,
new SelectList(Model.Customers.MembershipTypes, "Id", "Name"), "Select Membership Type",
new { #class = "form-control", #multiple = "multiple" })

FormMethod.Post returning 0

I have a problem with a FormMethod Post, I'm trying to post one single value (id) and store it in a Session variable, but the value return 0.
This is my code.
#foreach (var item in Model)
{
using (#Html.BeginForm("Index", "ProductSelec", FormMethod.Post))
{
#Html.HiddenFor(modelItem => item.id, new { value = "#Html.DisplayFor(modelItem => item.id)" })
<div class="AppOpt">
<button type="submit" name="submit" style="background-image: url('../Content/ICONS/SystemApp/#Html.DisplayFor(modelItem => item.img)');border-radius: 20px;background-size: cover;background-repeat: no-repeat;" class="AppImg">
<div class="OptNameRec">
<div class="OptIcon">
<img src='~/Content/ICONS/#Html.DisplayFor(modelItem => item.icon)'>
</div>
<div>
<p>#Html.DisplayFor(modelItem => item.nombre)</p>
</div>
<div class="clear"></div>
</div>
<div class="OptImage"></div>
</button>
</div>
}
}
The form is inside the foreach, becuase I'm creating the elements dinamically from a DB.
I want to store the item.id clicked.
This is my Controller
public ActionResult Index()
{
return View(db.aplicaciones.ToList());
}
public ActionResult ProductFamily()
{
return View();
}
[HttpPost]
public int Index(aplicaciones aplicaciones)
{
Session["appID"] = aplicaciones.id;
return aplicaciones.id;
}
and this is my Model.
public partial class aplicaciones
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public aplicaciones()
{
this.appNfam = new HashSet<appNfam>();
}
public int id { get; set; }
public string nombre { get; set; }
public string icon { get; set; }
public string img { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<appNfam> appNfam { get; set; }
}
I was trying to create another Model, but when I added, the foreach didn't read the values from the database.
I hope you can help me.
Change your controller method to:
[HttpPost]
public int Index(int id)
{
Session["appID"] = id;
return id;
}
Change your Html.BeginForm to be:
#using (Html.BeginForm("Index", "ProductSelec", new { id = item.id },FormMethod.Post, new { })
You should also be able to remove the hidden field since the ID will be posted by itself from your form action.

Why is this web http exception happening when I am populating a drop down list?

Model
League and LeagueDivision are two model classes
public class League
{
public int Id { get; set; }
public string League1 { get; set; }
public string Icon { get; set; }
public virtual ICollection<LeagueDivision> LeagueDivisions { get; set; }
}
public class LeagueDivision
{
public int Id { get; set; }
public Nullable<int> LeagueId { get; set; }
public string Name { get; set; }
public string Icon { get; set; }
public virtual League League { get; set; }
}
public class ViewModelForHostBooster
{
[Required(ErrorMessage = "Please enter price")]
[Display(Name = "Price")]
public decimal Price { get; set; }
[Required(ErrorMessage = "Please select a league")]
[Display(Name = "League")]
public int? SelectedLeague { get; set; }
[Required(ErrorMessage = "Please select a league division")]
[Display(Name = "League Division")]
public int? SelectedLeagueDivision { get; set; }
public SelectList LeagueList { get; set; }
public SelectList LeagueDivisionList { get; set; }
}
Controller
In IndexDropdown action I am just populating view with model and validating if
the model is validated then populate the view otherwise return the view. In FetchLeagueDivision action I am selecting Id and Name properties of model class based on passed argument ID.
Can anybody guide me why a WebHttpException is happening when I run this piece of code? Here is a link of exception Http Exception Image
public class DropDownController : Controller
{
[HttpGet]
public ActionResult IndexDropDown()
{
ViewModelForHostBooster model = new ViewModelForHostBooster();
ConfigureViewModel(model);
return View(model);
}
[HttpPost]
public ActionResult IndexDropDown(ViewModelForHostBooster model)
{
if (!ModelState.IsValid)
{
ConfigureViewModel(model);
return View(model);
}
// save and redirect
return RedirectToAction("Somewhere");
}
private void ConfigureViewModel(ViewModelForHostBooster model)
{
HostBoostersDBEntities db = new HostBoostersDBEntities();
var leagues = db.Leagues.Select(x => new { Value = x.Id, Text = x.League1 }).ToList();
model.LeagueList = new SelectList(leagues, "Id", "League1");
if (model.SelectedLeague.HasValue)
{
IEnumerable<LeagueDivision> leaguedivisions = db.LeagueDivisions.Where(l => l.LeagueId == model.SelectedLeague.Value);
model.LeagueDivisionList = new SelectList(leaguedivisions, "Id", "Name");
}
else
{
model.LeagueDivisionList = new SelectList(Enumerable.Empty<SelectListItem>());
}
}
}
View
#model HostBooster.Models.ViewModelForHostBooster
#using (Html.BeginForm())
{
<div>
#Html.LabelFor(m => m.Price)
#Html.TextBoxFor(m => m.Price)
#Html.ValidationMessageFor(m => m.Price)
</div>
<div>
#Html.LabelFor(m => m.SelectedLeague)
exception is occurring here #Html.DropDownListFor(m => m.SelectedLeague, Model.LeagueList)
#Html.DropDownListFor(m => m.SelectedLeague, Model.LeagueList)
#Html.ValidationMessageFor(m => m.SelectedLeague)
</div>
<div>
#Html.LabelFor(m => m.SelectedLeagueDivision)
#Html.DropDownListFor(m => m.SelectedLeagueDivision, Model.LeagueDivisionList)
#Html.ValidationMessageFor(m => m.SelectedLeagueDivision)
</div>
<input type="submit" value="save" />
}
In view Model.LeagueList is null. It should not be null.
if edit view code like this(for example), Works well:
<body>
#using (Html.BeginForm())
{
List<SelectListItem> listItems = new List<SelectListItem>();
listItems.Add(new SelectListItem
{
Text = "Example1",
Value = "Example1"
});
listItems.Add(new SelectListItem
{
Text = "Example2",
Value = "Example2",
Selected = true
});
listItems.Add(new SelectListItem
{
Text = "Example3",
Value = "Example3"
});
<div>
#Html.LabelFor(m => m.Price)
#Html.TextBoxFor(m => m.Price)
#Html.ValidationMessageFor(m => m.Price)
</div>
<div>
#Html.LabelFor(m => m.SelectedLeague)
#Html.DropDownListFor(m => m.SelectedLeague, listItems)
#Html.ValidationMessageFor(m => m.SelectedLeague)
</div>
<div>
#Html.LabelFor(m => m.SelectedLeagueDivision)
#Html.DropDownListFor(m => m.SelectedLeagueDivision, Model.LeagueDivisionList)
#Html.ValidationMessageFor(m => m.SelectedLeagueDivision)
</div>
<input type="submit" value="save" />
}

Cascading drop down wont populate MVC5

I am very new to MVC and I am trying to create a cascading drop down. The user will select the name of the practice and the drop down below will populate with the names of the opticians who work at that practice.
Optician Model:
public class Optician
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid OpticianId { get; set; }
[ForeignKey("User")]
public string UserId { get; set; }
public virtual ApplicationUser User { get; set; }
public IEnumerable<SelectListItem> UserList { get; set; }
[ForeignKey("Practice")]
public Guid PracticeId { get; set; }
public virtual Practice Practice { get; set; }
public IEnumerable<SelectListItem> PracticeList { get; set; }
public virtual ICollection<ApplicationUser> Users { get; set; }
public virtual ICollection<Practice> Practices { get; set; }
}
Practice Model:
public class Practice
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Display(Name = "Practice")]
public Guid PracticeId { get; set; }
[Display(Name = "Practice Name")]
public string PracticeName { get; set; }
public virtual ICollection<Optician> Opticians { get; set; }
public virtual ICollection<Booking> Bookings { get; set; }
}
Application User Model:
public class ApplicationUser : IdentityUser
{
[Display(Name = "Title")]
public string Title { get; set; }
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Display(Name = "Last Name")]
public string LastName { get; set; }
}
The Controller:
public ActionResult TestDropDown()
{
var practices = new SelectList(db.Practices, "PracticeId", "PracticeName");
ViewData["Practices"] = practices;
return View();
}
[HttpPost]
public JsonResult Opticians(Guid? Id)
{
var opticianList = db.Opticans.Where(a => a.PracticeId == Id).Select(a => a.User).ToList();
return Json(opticianList, JsonRequestBehavior.AllowGet);
}
The View:
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script>
$(document).ready(function () {
$("#Optician").prop("disabled", true);
$("#Practice").change(function () {
$.ajax({
url : "#Url.Action("Opticians","Bookings1")",
type : "POST",
data : {Id : $(this).val() }
}).done(function(OpticianList){
$("#Optician").empty();
for (var i = 0; i < OpticianList.length; i++) {
$("#Optician").append("<option>" + OpticianList[i].FirstName + "</option>");
}
$("#Optician").prop("disabled", false);
});
});
});
</script>
#using (Html.BeginForm("TestDropDown", "Bookings1", FormMethod.Post))
{
#Html.AntiForgeryToken()
<h4>Select Practcie & Opticians</h4>
<hr />
#Html.ValidationSummary()
<div class="form-group">
#Html.Label("Select Practice :", new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.DropDownList("PracticeId", ViewData["Practices"] as SelectList, new { #class = "form-control" })
</div>
</div><br />
<div class="form-group">
#Html.Label("Select Optician :", new { #class = "col-md-2 control-label" })
<div class="col-md-10">
<select id="Optician"></select>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-default" value="Submit" />
</div>
</div>
}
I can select the Name of the practice but the drop down for the Optician First Name does not populate.
Any help would be greatly appreciated
Thanks
You first <select> has id="PracticeId" but you script refers to an element with id="Practice" which does not exist, therefore is never run. Change you script to
var optician = $("#Optician"); // cache elements that you repeately refer to
optician.prop("disabled", true);
$("#PracticeId").change(function () { // change the selector
$.ajax({
url : "#Url.Action("Opticians","Bookings1")",
type : "POST",
data : {Id : $(this).val() }
}).done(function(OpticianList){
optician.empty();
for (var i = 0; i < OpticianList.length; i++) {
optician.append("<option>" + OpticianList[i].FirstName + "</option>");
}
optician.prop("disabled", false);
});
});
or you could just use the .getJSON() shortcut
$.getJSON('#Url.Action("Opticians","Bookings1")', { Id : $(this).val() }, function(OpticianList) {
// add the option elements
}
Since you only need the FirstName property of ApplicationUser, your controller code should be
var opticianList = db.Opticans.Where(a => a.PracticeId == Id).Select(a => a.User.FirstName)
and the script adjusted to
optician.append("<option>" + OpticianList[i] + "</option>");
or
optician.append($('<option></option>').text(OpticianList[i]));
so your not sending back a whole lot of extra data across the wire that you never use.
Try this in your action:
[HttpPost]
public JsonResult Opticians(Guid? Id)
{
var opticianList = db.Opticans.Where(a => a.PracticeId == Id).Select(a => a.User).ToList();
SelectList mySelectList = new SelectList(opticianList, "IDField", "DisplayField", 0);
return Json(mySelectList );
}
Here is the post I followed when I implemented this.
Fill drop down list on selection of another drop down list

Categories

Resources