简体   繁体   中英

POST Model(DTO) with List to controller

My project is MVC.Net Core project with Razor pages.

My Dto class:

public class TicketDto
{
    public Guid Id { get; set; }

    public IList<KeyValuePair<int, string>> Areas { get; set; }
}

In view i create select list using @Html.ListBoxFor

@Html.ListBoxFor(model => model.Areas, (MultiSelectList)ViewBag.AreaId, new { @class="custom-select", @id="inputGroupSelect01", size = 5 })

View also has ViewData/ViewBag:

ViewData["AreaId"] = new MultiSelectList(areaService.GetAreas().Select( a => new { a.Id, a.Name }), "Id", "Name");

Razor render next:

<select class="custom-select" id="inputGroupSelect01" multiple="multiple" name="Areas" size="5"><option value="1">A</option>
<option value="2">P</option>
<option value="3">S</option>
<option value="10">AB</option>
<option value="11">AB</option>
</select>

image of select list

Controler takes TicketDto:

public IActionResult Create(TicketDto ticketDto)

When i select multiple items and POST form to controller the ticketDto.Areas count = 0

How shoud i post model class with List and @Html.ListBoxFor choice to my controller?

Multiselectlist will post through an array of the selected values by default. If you want to get all the selected items it could be done like this:

public class MyData
{
   public string Id { get; set; }
   public string Value { get; set; }
}
public class MyViewModel
{
    public int[] SelectedIds { get; set; }
    public IEnumerable<SelectListItem> Items { get; set; }
}

public IActionResult Index()
{
   var data = new List<MyData>
   {
       new MyData() {Id = "2", Value = "P"}, new MyData() {Id = "3", Value = "S"},
       new MyData() {Id = "10", Value = "AB"}
   };
   var model = new MyViewModel
   {
       Items = data.Select(x => new SelectListItem
       {
          Value = x.Id,
          Text = x.Value
       })
    };
    return View(model);
  }

 public IActionResult Create(MyViewModel model)

 @using (Html.BeginForm("Create", "Home", FormMethod.Post))
 {
    @Html.ListBoxFor(x => x.SelectedIds, Model.Items)
    <p><input type="submit" value="Submit" /></p>
 }

在此处输入图像描述

Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM