What is the best ways to bind @Html.DropDownListFor in ASP.NET MVC5?

The strongly typed view model approach which does not use dynamic stuff like ViewBag You can add a new property to your view model for the SELECT options of type IEnumrable<SelectListItem>. view model is a simple POCO class used to transfer data between view to action method and vice versa. They are specific to the … Read more

onchange event for html.dropdownlist

If you don’t want jquery then you can do it with javascript :- @Html.DropDownList(“Sortby”, new SelectListItem[] { new SelectListItem() { Text = “Newest to Oldest”, Value = “0” }, new SelectListItem() { Text = “Oldest to Newest”, Value = “1” }, new { @onchange=”callChangefunc(this.value)” } }); <script> function callChangefunc(val){ window.location.href = “/Controller/ActionMethod?value=” + val; } … Read more

Create a Dropdown List for MVC3 using Entity Framework (.edmx Model) & Razor Views && Insert A Database Record to Multiple Tables

Don’t pass db models directly to your views. You’re lucky enough to be using MVC, so encapsulate using view models. Create a view model class like this: public class EmployeeAddViewModel { public Employee employee { get; set; } public Dictionary<int, string> staffTypes { get; set; } // really? a 1-to-many for genders public Dictionary<int, string> … Read more

Fill drop down list on selection of another drop down list [closed]

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 … Read more

Populating a razor dropdownlist from a List in MVC

You can separate out your business logic into a viewmodel, so your view has cleaner separation. First create a viewmodel to store the Id the user will select along with a list of items that will appear in the DropDown. ViewModel: public class UserRoleViewModel { // Display Attribute will appear in the Html.LabelFor [Display(Name = … Read more

Can the ViewBag name be the same as the Model property name in a DropDownList?

You should not use the same name for the model property and the ViewBag property (and ideally you should not be using ViewBag at all, but rather a view model with a IEnumerable<SelectListItem> property). When using @Html.DropDownListFor(m => m.CustomerId, ….) the first “Please Select” option will always be selected even if the value of the … Read more