Create DropDownListFor from SelectList with default value

前端 未结 5 1208
花落未央
花落未央 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<Status> 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.

    0 讨论(0)
  • 2021-01-05 08:38

    There exist already some discussions about that here or there. One of the problems might be using a different type than string for the key value. I had similar problems in past and I know that i solved it like this - explicitly setting the Selected property when preparing the list (in your case, AlLStatus).

    Would mean, for your case (in controller action):

    IEnumerable<SelectListItem> selectList = 
    from s in allStatus // where ever you get this from, database etc.
    select new SelectListItem
    {
        Selected = (s.id == model.Item.Item.Status),
        Text = cs.Description,
        Value = s.id.ToString()
    };
    model.AllStatus = selectList;
    
    0 讨论(0)
  • 2021-01-05 08:38

    I ended up using a variant of thomasjaworski's answer.

    View:

    @Html.DropDownListFor(model => model.SelectedStatusIndex, new SelectList(@Model.StatusSelectList, "Value", "Text"), new { id = "statusDropdown" })
    

    ViewModel constructor

            StatusSelectList = AllStatus.Select(x =>
                                            new StatusSelectListItem
                                            {
                                                Text = x.Description,
                                                Value = x.id.ToString()
                                            }).ToList();
    
            this.SelectedStatusIndex = 2;//Default Status is New
    

    Controller on HTTP POST

    I set model.Item.Item.Status seperately from the dropdown itself:

    model.Item.Item.Status = model.SelectedStatusIndex;
    

    because the dropdown set's the value of the expression passed as the first argument:

    @Html.DropDownListFor(model => model.SelectedStatusIndex, new SelectList(@Model.StatusSelectList, "Value", "Text"), new { id = "statusDropdown" })
    

    In this case model.SelectedStatusIndex is what is set by the dropdown. This controller implementation is what I found to be tricky.

    0 讨论(0)
  • 2021-01-05 08:39

    You can use "Insert" for adding default value of Dropdown and add it to your Dynamic list : By this way you don't need to use Razor in your View.

    List<Y> m = X.GetList();
    m.Insert(0, new Y{ Name = "--Select--" });
    
    0 讨论(0)
  • 2021-01-05 08:53
    SelectList ProductSizeList = new SelectList(_context.Sizes, "SizeId", "SizeName");
    
    //after you create the selectList you have to create the default select list item            
    SelectListItem AllSize = new SelectListItem("All Size", "0");
    
    // and after this you add this item to the begin of the selectlist
    ViewData["SizeId"] = ProductSizeList.Prepend(AllSize);
    
    0 讨论(0)
提交回复
热议问题