带有控制器列表的POST模型(DTO)

问题描述 投票:0回答:1

我的项目是带有Razor页面的MVC.Net Core项目。

我的Dto班级:

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

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

在视图中,我使用@ Html.ListBoxFor创建选择列表] >>

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

视图还具有ViewData / ViewBag:

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

剃刀渲染下一个:

<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

控制者将TicketDto带到:

public IActionResult Create(TicketDto ticketDto)

当我选择多个项目并以POST形式控制ticketDto.Areas

计数= 0

我应该如何将具有List@ Html.ListBoxFor

选择的模型类发布到我的控制器?

我的项目是带有Razor页面的MVC.Net Core项目。我的Dto类:公共类TicketDto {public Guid Id {get;组; } public IList > Areas {get;设置; ...

c# asp.net-mvc-4 razor .net-core dto
1个回答
0
投票

Multiselectlist默认情况下将通过选定值的数组进行发布。如果要获取所有选定的项目,可以这样进行:

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>
 }
© www.soinside.com 2019 - 2024. All rights reserved.