【问题标题】:Bind list of object to Multi selection of DropdownlistFor and Submitform将对象列表绑定到 DropdownlistFor 和 Submitform 的多选
【发布时间】:2015-10-25 15:23:23
【问题描述】:

我有两节课

class UserRequestModel
{
    public UserRequestModel()
    {
        ProfileRequest = new List<ProfileRequestModel>();
    }

    public int ID { get; set; }
    public List<ProfileRequestModel> ProfileRequest { get; set; }
}

public class ProfileRequestModel
{
    public int ProfileID { get; set; }
    public string ProfileName { get; set; }
}
  1. 我想使用 UserRequestModel 作为模型。
  2. 如何绑定Dropdownlistfor的多选?
  3. 在提交表单上,在控制器中 公共 ActionResult SubmitForm(UserRequestModel obj) obj 应该包含多个选定的值。

【问题讨论】:

  • Class 还是class
  • @Cristian Ciupitu,上课了

标签: asp.net-mvc asp.net-mvc-4


【解决方案1】:

您有以下两种选择:

  1. 使用@Html.ListBox 将选项呈现为多个值 下拉菜单。

    因此,您视图中的代码如下所示:

    @Html.ListBox(ViewBag.ProfileRequest as SelectList, new { @id = "ProfileRequest" })
    
  2. 其他选项是使用jquery.multiSelect.js,可以找到 here.

    所以你的列表框将由这个插件呈现,如下所示:

    <script src="@Url.Content("~/Scripts/jquery.multiSelect.js")" type="text/javascript"></script>
    <script type="text/javascript">
    $(function () {
        $("#SelectedValues").multiSelect();
    });
    </script>
    
    
    @using (Html.BeginForm())
    {
        @Html.ListBoxFor(x => x.SelectedValues, Model.ProfileRequest)
        <button type="submit">OK</button>
    }
    

    接下来您可以发布您的视图模型

    [HttpPost]
    public ActionResult Index(UserRequestModel model)
    {
      return View(model);
    }
    

参考文章 http://www.aspnetmvcninja.com/views/asp-net-mvc-select-list-example

【讨论】:

  • 谢谢。使用 UserRequestModel 我将获得配置文件的 ID 和列表然后我如何将多个配置文件绑定到下拉列表中
  • 您的下拉列表将绑定到 ProfileRequestModel @Html.ListBoxFor(model =&gt; model.SelectedValues, new SelectList(Model.ProfileRequest, "Value", "Text")) 然后获取选定的值 var sports = string.Join(",", model.SelectedValues)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多