MVC Select a list with a model for postback, how?

I'm trying to create a view that will require two drop-down lists with MVC 3. In my only other MVC application, we used Telerik elements that used the Ajax method to populate the data. Now in this project we do not use third-party controls, so I will use the MVC SelectList drop-down list. I read a lot of articles on how to populate a SelectList , but none of them say the same thing twice, there is always another way to create a model, some use ViewData or ViewBag to store collections and go to the view, etc. no coherence.

What is the best way to populate a drop-down list in an MVC view that uses the model itself for data, not ViewData . And when the user makes a choice from the list, sends and calls the HttpPost action, how can I access the selected value from the Model property of the selection list property?

This is my current model:

 public class TemporaryRegistration { [Required] [Email(ErrorMessage = "Please enter a valid email address.")] [Display(Name = "Email address")] public string Email { get; set; } [Required] [Integer] [Min(1, ErrorMessage = "Please select an entity type.")] [Display(Name = "Entity Type")] public IEnumerable<SelectListItem> EntityType { get; set; } [Required] [Integer] [Min(1, ErrorMessage = "Please select an associated entity.")] [Display(Name = "Associated Entity")] public IEnumerable<SelectListItem> AssociatedEntity { get; set; } } 

This is my current view, it only uses TextBoxFor , where I need to use the drop-down menus, how do I turn them into drop-down lists?

 @model Web.Models.TemporaryRegistration <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script> @using (Html.BeginForm()) { @Html.ValidationSummary(true) <fieldset> <legend>Create New ELM Select User</legend> <div class="editor-label"> @Html.LabelFor(model => model.Email) </div> <div class="editor-field"> @Html.EditorFor(model => model.Email) @Html.ValidationMessageFor(model => model.Email) </div> <div class="editor-label"> @Html.LabelFor(model => model.EntityType) </div> <div class="editor-field"> @Html.EditorFor(model => model.EntityType) @Html.ValidationMessageFor(model => model.EntityType) </div> <div class="editor-label"> @Html.LabelFor(model => model.AssociatedEntity) </div> <div class="editor-field"> @Html.EditorFor(model => model.AssociatedEntity) @Html.ValidationMessageFor(model => model.AssociatedEntity) </div> <p> <input type="submit" value="Create" /> </p> </fieldset> } <div> @Html.ActionLink("Back to List", "Index") </div> 

This is my current Post action: How to get selected values?

 [HttpPost] public ActionResult CreateUser(TemporaryRegistration registrationModel) { string newRegistrationGUID = string.Empty; if (!ModelState.IsValid) { return View(); } TemporaryRegistrationEntity temporaryRegistration = null; temporaryRegistration = new TemporaryRegistrationEntity(registrationModel.Email, registrationModel.EntityType, registrationModel.AssociatedEntity); newRegistrationGUID = temporaryRegistration.Save(); return Content("New registration was created with GUID " + newRegistrationGUID); } 
+4
source share
2 answers

Continuing the comment ...

Say you have a model called Toy . The toy has properties such as Name , Price and Category :

 public class Toy() { public string Name; public double Price; public string Category } 

Now you want to create a View form for adding Toy , and people should be able to select a category from the drop-down list of features ... but you don’t want to do this through ViewData or ViewBag for any reason.

Instead of passing the model to the view, create a ToyViewModel that has a Name , Price , Category ... but also has a set of categories to populate the drop-down list:

 public class ToyViewModel() { public string Name; public double Price; public string Category public ICollection<string> Categories; } 

Now your controller does this:

 public ActionResult GetToyForm() { var viewModel = new ToyViewModel(); viewModel.Categories = _service.GetListOfCategories(); return View(viewModel); } 

Your view is associated with the ViewModel, and you use the model.Categories collection to populate the drop-down list. It should look something like this:

 @Html.DropDownListFor(model => model.Category, model.Categories) 

When you submit it, your controller does something like:

 [HttpPost] public ActionResult CreateToy(ToyViewModel _viewModel) { var model = new Toy(); model.Name = _viewModel.Name // etc. _service.CreateToy(model); // return whatever you like. return View(); } 

It’s good practice to create ViewModels to bind to Views so that you can adapt them to the needs of your view level, while your models stay close to the data level and business logic.

+8
source

EntityType does not have to be a list unless you take multiple values ​​back (for example, a list field sends). When you show a drop-down list (which usually selects only one value) in the view, you just need to provide its options in another way, for example, send the list to another property of the view model.

 public class TemporaryRegistration { [Required] [Email(ErrorMessage = "Please enter a valid email address.")] [Display(Name = "Email address")] public string Email { get; set; } [Required] [Integer] [Min(1, ErrorMessage = "Please select an entity type.")] [Display(Name = "Entity Type")] public int EntityType { get; set; } public IEnumerable<SelectListItem> EntityTypes { get; set; } [Required] [Integer] [Min(1, ErrorMessage = "Please select an associated entity.")] [Display(Name = "Associated Entity")] public IEnumerable<SelectListItem> AssociatedEntity { get; set; } } 

Then use the drop down list helper list.

 @Html.DropDownListFor(model => model.EntityType, model.EntityTypes) 
+2
source

Source: https://habr.com/ru/post/1389531/


All Articles