MVC DropDownList SelectedValue not displaying correctly

后端 未结 7 940
甜味超标
甜味超标 2020-12-01 12:40

I tried searching and didn\'t find anything that fixed my problem. I have a DropDownList on a Razor view that will not show the the item that I have marked as Selected in th

7条回答
  •  不思量自难忘°
    2020-12-01 13:07

    Create a view model for each view. Doing it this way you will only include what is needed on the screen. As I don't know where you are using this code, let us assume that you have a Create view to add a new order.

    Create a new view model for your Create view:

    public class OrderCreateViewModel
    {
         // Include other properties if needed, these are just for demo purposes
    
         // This is the unique identifier of your order status,
         // i.e. foreign key in your order table
         public int OrderStatusId { get; set; }
         // This is a list of all your order statuses populated from your order status table
         public IEnumerable OrderStatuses { get; set; }
    }
    

    Order status class:

    public class OrderStatus
    {
         public int Id { get; set; }
         public string Name { get; set; }
    }
    

    In your Create view you would have the following:

    @model MyProject.ViewModels.OrderCreateViewModel
    
    @using (Html.BeginForm())
    {
         
    Order Status: @Html.DropDownListFor(x => x.OrderStatusId, new SelectList(Model.OrderStatuses, "Id", "Name", Model.OrderStatusId), "-- Select --" ) @Html.ValidationMessageFor(x => x.OrderStatusId)
    }

    Your Create action methods:

    public ActionResult Create()
    {
         OrderCreateViewModel viewModel = new OrderCreateViewModel
         {
              // Here you do database call to populate your dropdown
              OrderStatuses = orderStatusService.GetAllOrderStatuses()
         };
    
         return View(viewModel);
    }
    
    [HttpPost]
    public ActionResult Create(OrderCreateViewModel viewModel)
    {
         // Check that viewModel is not null
    
         if (!ModelState.IsValid)
         {
              viewModel.OrderStatuses = orderStatusService.GetAllOrderStatuses();
    
              return View(viewModel);
         }
    
         // Mapping
    
         // Insert order into database
    
         // Return the view where you need to be
    }
    

    This will persist your selections when you click the submit button and is redirected back to the create view for error handling.

    I hope this helps.

提交回复
热议问题