Create DropDownListFor from SelectList with default value

前端 未结 5 1211
花落未央
花落未央 2021-01-05 08:33

I have a dropdownlistfor:

 @Html.DropDownListFor(model => model.Item.Item.Status, new SelectList(@Model.AllStatus, \"id\", \"Description\"),          


        
5条回答
  •  广开言路
    2021-01-05 08:35

    This is in addition to the answers above. This is how I would have done it.

    The view model is there to represent your data. So for a single drop down list I would have the following:

    public class MyViewModel
    {
         public int StatusId { get; set; }
    
         public IEnumerable Statuses { get; set; }
    }
    

    And the Status class would look like this:

    public class Status
    {
         public int Id { get; set; }
    
         public string Description { get; set; }
    }
    

    The controller's action method to handle the view:

    public class MyController
    {
         private readonly IStatusService statusService;
    
         public MyController(IStatusService statusService)
         {
              this.statusService = statusService;
         }
    
         public ActionResult MyActionMethod()
         {
              MyViewModel viewModel = new MyViewModel
              {
                   Statuses = statusService.GetAll(),
                   StatusId = 4 // Set the default value
              };
    
              return View(viewModel);
         }
    }
    

    The view will look like this:

    @model MyProject.ViewModels.MyViewModel
    
    @Html.DropDownListFor(
         x => x.StatusId,
         new SelectList(Model.Statuses, "Id", "Description", Model.StatusId),
         "-- Select --"
    )
    @Html.ValidationMessageFor(x => x.StatusId)
    

    There you go.

提交回复
热议问题