Daniil Basanets
Daniil Basanets

Reputation: 3

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?

Upvotes: 0

Views: 987

Answers (1)

Eugene
Eugene

Reputation: 421

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>
 }

enter image description here

Thanks

Upvotes: 0

Related Questions