如何在剃刀中获取所有选中的复选框

时间:2016-06-30 09:56:58

标签: c# html asp.net-mvc razor checkbox

使用复选框,并将传输选中的复选框粘贴到后端。我知道如何做到这一点,但我想听听其他变种。所以我有一张带有复选框的表格:

<td>
    <input type="checkbox" class="check" value="@item.Id"/>
</td>

并提交按钮

@Html.ActionLink("delete", "DeleteSelectedPictures")

所以我的变体是添加bool属性并将表从input更改为@html.checkboxfor(_ => _.selected),然后如何获取这些选定的项目?还有其他方式如何解决这个问题?

//控制器逻辑

public ActionResult DeleteSelectedPictures(int itemsId)
{
    var pictures = from items in _Db.Pictures
                   where items.Id == itemsId
                   select items;

    foreach (var picture in pictures)
    {
        _Db.Pictures.Remove(picture);
    }

    return RedirectToAction("Index");
}

upd 2。

由于 Ali sultani 建议,这里有更新,但有问题,请从此处开始为空var selected = Request.Form["chkPicture"];

cshtml:

 <div>
    @using (Html.BeginForm())
    {
        <table id="images">
            <tbody>
            @foreach (var item in Model.Pictures.Where(o => o.PartnerId == Model.PartnerId && !o.IsDeleted))
            {
                <tr>
                    <td>
                        <input name="chkPicture" type="checkbox" class="check" value="@item.Id"/>
                    </td>
                    <td>
                        <img src="@(Model.BaseUrl)GetPreview.ashx?h=200&id=@item.Id&w=200"/>
                    </td>
                </tr>
            }
            </tbody>
        </table>

        <div id="container">
            @Html.ActionLink(R("Remove"), "DeleteSelectedPictures")
        </div>

    }
</div>

和cs控制器:

public ActionResult DeleteSelectedPictures()
    {
        var selected = Request.Form["chkPicture"];
        var selectedList = selected.Split(',');
        foreach (var temp in selectedList)
        {
            var strTemp = Convert.ToInt32(temp);
            var deletePicture = _Db.Pictures.FirstOrDefault(p => p.Id == strTemp);
            _Db.Pictures.Remove(deletePicture);
            _Db.SaveChanges();
        }
        return RedirectToAction("Index");
    }

3 个答案:

答案 0 :(得分:3)

你可以这样做:

查看:

<body>
    @using (Html.BeginForm())
    {

        <table class="table">
            <tr>
                <th>
                    @Html.DisplayNameFor(model => model.Name)
                </th>
                <th></th>
            </tr>

            @foreach (var item in Model)
            {
                <tr>
                    <td>
                        @Html.DisplayFor(modelItem => item.Name)

                    </td>
                    <td>
                        <input name="chkPicture" type="checkbox" class="check" value="@item.Id" />
                    </td>

                </tr>
            }

        </table>
        <input type="submit" value="Delete" />
    }
</body>

动作:

public ActionResult GetCheckBox()
    {
        Entities db = new Entities();
        var Pictures = db.Pictures.ToList();
        return View(Pictures);
    }

[HttpPost]
    public ActionResult GetCheckBox(FormCollection form)
    {
        string selected = Request.Form["chkPicture"].ToString();
        string[] selectedList = selected.Split(',');
        foreach (var temp in selectedList)
        {
            Entities db = new Entities();
            int strTemp = Convert.ToInt32(temp);
            Picture DeletePic = db.Pictures.Where(p => p.Id == strTemp).FirstOrDefault();
            db.Pictures.Remove(DeletePic);
            db.SaveChanges();
        }
        return View();
    }

答案 1 :(得分:0)

在视图模型中使用字符串数组。然后,您可以使用我一起攻击的帮助程序。如果你不想使用帮助器和枚举,那么在底部看到实际的Html。绑定器将返回一个字符串数组,其中只包含选定的字符串值。如果未选中,则返回数组的空值。你必须考虑到这一点,你已被警告:)

View Model:
        [Display(Name = "Which Credit Cards are Accepted:")]
        public string[] CreditCards { get; set; }

    Helper:
        public static HtmlString CheckboxGroup<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> propertySelector, Type EnumType)
        {
            var groupName = GetPropertyName(propertySelector);
            var modelValues = ModelMetadata.FromLambdaExpression(propertySelector, htmlHelper.ViewData).Model;//propertySelector.Compile().Invoke(htmlHelper.ViewData.Model);
        StringBuilder literal = new StringBuilder();  

        foreach (var value in Enum.GetValues(EnumType))
        {
            var svalue = value.ToString();
            var builder = new TagBuilder("input");
            builder.GenerateId(groupName);
            builder.Attributes.Add("type", "checkbox");
            builder.Attributes.Add("name", groupName);
            builder.Attributes.Add("value", svalue);
            var contextValues = HttpContext.Current.Request.Form.GetValues(groupName);
            if ((contextValues != null && contextValues.Contains(svalue)) || (modelValues != null && modelValues.ToString().Contains(svalue)))
            {
                builder.Attributes.Add("checked", null);
            }

            literal.Append(String.Format("</br>{1}&nbsp;<span>{0}</span>", svalue.Replace('_', ' '),builder.ToString(TagRenderMode.Normal)));
        }

        return (HtmlString)htmlHelper.Raw(literal.ToString()); 
    }

    private static string GetPropertyName<T, TProperty>(Expression<Func<T, TProperty>> propertySelector)
    {
        var body = propertySelector.Body.ToString();
        var firstIndex = body.IndexOf('.') + 1;
        return body.Substring(firstIndex);
    }

HTML:

@Html.CheckboxGroup(m => m.CreditCards, typeof(VendorCertification.Enums.CreditCardTypes))

如果帮助程序扩展吓到你,请使用此方法:

            <input id="CreditCards" name="CreditCards" type="checkbox" value="Visa" 
            @(Model.CreditCards != null && Model.CreditCards.Contains("Visa") ? "checked=true" : string.Empty)/>
            &nbsp;<span>Visa</span><br />

            <input id="CreditCards" name="CreditCards" type="checkbox" value="MasterCard" 
            @(Model.CreditCards != null && Model.CreditCards.Contains("MasterCard") ? "checked=true" : string.Empty)/>
            &nbsp;<span>MasterCard</span><br />

答案 2 :(得分:-1)

通过ajax.begin表单

修复了这个问题
@using (Ajax.BeginForm("DeleteSelectedDecorPictures", new AjaxOptions() { UpdateTargetId = "updateId" }))
{
    <div>
        <div id="updateId"></div>
        <table id="images">
            <tbody>
                @foreach (var item in Model.Pictures.Where(o => o.PartnerId == Model.PartnerId && !o.IsDeleted))
                {
                    <tr>
                        <td>
                            <input name="chkPicture" type="checkbox" class="check" value="@item.Id" />
                        </td>
                        <td>
                            <img src="@(Model.BaseUrl)GetPreview.ashx?h=200&id=@item.Id&w=200" />
                        </td>
                    </tr>
                }
            </tbody>
        </table>

        <div id="container">
            <div id="filelist"></div>
            <h1>
                <input id="delSelected" type="submit" value="Remove Selected" />
            </h1>
        </div>


    </div>
}