从CheckboxList MVC.NET Razor中获取所选项目

时间:2013-08-12 07:25:01

标签: c# asp.net-mvc razor selecteditem

我有以下cshtml表单

@using (Html.BeginForm(Html.BeginForm("Create", "UserRole", Model, FormMethod.Post)))
{
   @Html.AntiForgeryToken()
   @Html.ValidationSummary(true)

   <fieldset>
       <legend>Role</legend>

       <div class="editor-label">
           @Html.Label(Model.User.UserName)
       </div>
       <div class="editor-field">
           @Html.CheckBoxList(Model.CheckboxList)
       </div>

       <p>
           <input type="submit" value="Create" />
       </p>
   </fieldset>
}

我希望在我的操作中选择Model.CheckboxList。

我的控制器中有以下创建操作

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(UserRoleViewModel userRoleViewModel)
    {
        if (ModelState.IsValid)
        {
            //_context.Role.Add(role);
            //_context.SaveChanges();
            //return RedirectToAction("Index");
        }

        return View(viewModel);
    }

但是viewModel.CheckboxList为0。

如何将复选框列表的选定值以及Model.User传递给Controller Action?

我的ViewModel如下所示: -

    public User User { get; set; }
    public IEnumerable<Role> RoleList { get; set; }

    public List<UserRoleViewModel> UserList { get; set; }

    public IEnumerable<SelectListItem> CheckboxList { get; set; }

    public UserRoleViewModel()
    {
    }

    public UserRoleViewModel(User user, IEnumerable<Role> roleList )
    {
        User = user;
        RoleList = roleList;
    }

感谢您的帮助和时间!

更新-----------阅读此帖enter link description here后,我尝试调整我的代码以遵循示例,但我仍然发现此更新代码存在问题。

现在我有以下内容: -

cshtml: -

@model IEnumerable<MvcMembership.ViewModels.RoleCheckboxListViewModel>

    @using (Html.BeginForm())
    {
        @Html.EditorForModel()
        <input type="submit" value="OK" />
    }

浏览/角色/ EditorTemplates / RoleCheckboxListViewModel.cshtml

@model MvcMembership.ViewModels.RoleCheckboxListViewModel
@Html.HiddenFor(x => x.RoleId)
@Html.HiddenFor(x => x.RoleName)
<div>
   @Html.CheckBoxFor(x => x.Checked)
   @Html.LabelFor(x => x.Checked, Model.RoleName)
</div>

ViewModels: -

public class RoleCheckboxListViewModel
{
    public string RoleId { get; set; }
    public string RoleName { get; set; }
    public bool Checked { get; set; }
}

并且控制器操作如下: -

        public ActionResult Create(int? uid)
    {
        var checkBoxList = new[]
        {
            new RoleCheckboxListViewModel() { 
                    RoleId = "1", Checked = true, RoleName = "item 1"  },
            new RoleCheckboxListViewModel() { 
                    RoleId = "2", Checked = true, RoleName = "item 2" },
            new RoleCheckboxListViewModel() { 
                    RoleId = "3", Checked = true, RoleName = "item 3" },
        };

        return View(checkBoxList);
    }

我现在遇到的问题是Create.cshtml。我看不到复选框列表,但只显示了123和OK按钮。

任何帮助都会非常感激,因为我现在处于死路。

2 个答案:

答案 0 :(得分:6)

我用以下部分完成了这个:

1)子元素的视图模型,它添加了bool属性,该属性将表示是否在View中查看复选框...即:

public class CategoryViewModel
{
    public int ID { get; set; }
    public string Name { get; set; }
    public bool Assigned { get; set; }
}

2)父元素的视图模型,它为这个新的子元素视图模型添加了一个集合属性,即:

public class ManufacturerViewModel
    {
        public Manufacturer Manufacturer { get; set; }
        public IList<CategoryViewModel> Categories { get; set; }

        public ManufacturerViewModel()
        {
            Categories = new List<CategoryViewModel>();
        }
    }

3)一种服务层方法,用于获取所有子元素的列表,同时还为每个子元素设置bool属性(在我的示例中为“Assigned”)。供您的控制器使用。

public IList<CategoryViewModel> GetCategoryAssignments(Manufacturer mfr)
        {
            var categories = new List<CategoryViewModel>();
            foreach (var category in GetCategories())
            {
                categories.Add(new CategoryViewModel
                {
                    ID = category.ID,
                    Name = category.Name,
                    Assigned = mfr.Categories.Select(c => c.ID).Contains(category.ID)
                });
            }
            return categories;
        }

4)根据您的复选框列表选择更新父项集合的方法。供您的控制器使用。

public void UpdateCategories(string[] selectedCategories, ManufacturerViewModel form)
        {
            if (selectedCategories == null)
                selectedCategories = new string[] { };
            var selectedIds = selectedCategories.Select(c => int.Parse(c)).ToList();
            var assignedIds = form.Manufacturer.Categories.Select(c => c.ID).ToList();
            foreach (var category in GetCategories())
            {
                if (selectedIds.Contains(category.ID))
                {
                    if (!assignedIds.Contains(category.ID))
                        form.Manufacturer.Categories.Add(category);
                }
                else
                {
                    if (assignedIds.Contains(category.ID))
                        form.Manufacturer.Categories.Remove(category);
                }
            }
        }

5)修改“创建/编辑”视图。即:

@Html.EditorFor(model => model.Categories)

您还必须添加此项,以便原始分配的值包含在发布数据中。您必须为已通过验证设置为必需的每个属性添加HiddenFor。

for (int i = 0; i < Model.Manufacturer.Categories.Count; i++)
    {
        @Html.HiddenFor(model => model.Manufacturer.Categories[i].ID);
        @Html.HiddenFor(model => model.Manufacturer.Categories[i].Name);
    }

6)最后,为您的子视图模型元素创建一个新的EditorTemplate。即:

@model YourProject.ViewModels.CategoryViewModel
<li>
    <input type="checkbox" 
        id="@string.Format("cb{0}{1}", @Model.Name, @Model.ID)" 
        name="selectedCategories" //Notice this name corresponds to string[] selectedCategories so that it can be extracted from the post data
        value="@Model.ID"
        @(Html.Raw(Model.Assigned ? "checked=\"checked\"" : "")) />
    <label for="@string.Format("cb{0}{1}", @Model.Name, @Model.ID)">@Model.Name</label>
    @Html.HiddenFor(model => model.ID)
</li>

希望我自己的应用程序能让您更好地了解如何解决此问题。

答案 1 :(得分:2)

将您选择的值存储到变量中,如下所示,并将其传递给隐藏字段,然后您可以轻松访问它

var modelSelected = document.getElementById("modelName");
document.getElementById('selectedModel').value =
   modelSelected.options[modelSelected.selectedIndex].text;

<input id="selectedModel" name="selectedModel" type="hidden" runat="server" />