0
votes

I want to bind a pre-defined list of string values to a form control in order that the user is forced to select from the list as apposed to entering their own values. The list should be accessible for both the Create and Edit Razor pages in a CRUD EF Core environment. Once the item from the list is selected then this string is used as the input value for saving to the database.

The code snippet below simply shows a standard text input control but instead I just was a dropdown list with predefined values:

 <div class="form-group">
            <label asp-for="ConnectorModel.ConnectorType" class="control-label"></label>
            <input asp-for="ConnectorModel.ConnectorType" class="form-control" />
            <span asp-validation-for="ConnectorModel.ConnectorType" class="text-danger"></span>
        </div>

I previously used the following code which changed the input control into a dropdown list type, but I had no idea how to fill it with the items from the list. I think im right in saying that viewbag is the wrong type to use as well.

 <div class="form-group">
            <label asp-for="ConnectorModel.ConnectorType" class="control-label"></label>
             <select asp-for="ConnectorModel.ConnectorType" class="form-control" asp-items="ViewBag.ConnectorType"></select>
            <span asp-validation-for="ConnectorModel.ConnectorType" class="text-danger"></span>
        </div>
1

1 Answers

1
votes

In order to have a drop down you should use <select> tag. You can fill a <select> pretty simple with tag helpers (asp-*). The standard type for filling dropdowns is SelectListItem. The view will be something like this:

@page
@model IndexModel
<form method="post">
  <select asp-items="@Model.StringItems" asp-for="@Model.SelectedString" />
  <button type="submit">Submit</button>
</form>

And the page model:

public class IndexModel : PageModel
{
   public IEnumerable<SelectListItem> StringItems { get; private set; }

   [BindProperty] 
   public string SelectedString { get; set; }

   public void OnGet()
   {
      // prepare the list in here
      StringItems = new SelectListItem[]
      {
         new SelectListItem ("Text1", "Value1"),
         new SelectListItem ("Text2", "Value2"),
         new SelectListItem ("Text3", "Value3")
      }
   }

   public void OnPost()
   {
      // use the selected item in post. 
      // it will be set in the SelectedString 
   }
}