【问题标题】:how to get all selected checkboxes in razor如何在剃刀中获取所有选中的复选框
【发布时间】:2016-11-02 08:25:38
【问题描述】:

使用复选框,并坚持将选定的复选框传输到后端。我知道如何做到这一点,但我想听听其他变体。所以我有一个带有复选框的表格:

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

并提交按钮

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

所以我的变体是添加布尔属性并将表从input更改为@html.checkboxfor(_ =&gt; _.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");
}

更新 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");
    }

【问题讨论】:

  • 如果您使用多个复选框,请使用 CheckboxList。
  • 你能粘贴你的控制器逻辑吗?
  • @Anonymous,帖子已更新。但我认为这行不通...因为我需要转移一组选定的项目..
  • @Abdul,你能举个例子吗?我应该在模型中为复选框列表中的 labmda 表达式设置属性吗?
  • 请参考我的stackoverflow帖子:Here

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


【解决方案1】:

你可以这样做:

查看:

<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();
    }

【讨论】:

  • 请查看更新 2
  • @Vitaliy 添加使用 (Html.BeginForm()) 来查看。
  • @Vitaliy 我在我的系统中测试了这段代码并获得了选中的复选框。我认为这个问题在你看来。请完全更新视图代码。
  • 你可以使用 input type = submit,你也应该像这样编辑 Html.BeginForm:@using (Html.BeginForm("Action name", "controller name"))
  • @Vitaliy 如果这个答案对你有帮助,请点赞并接受这个答案,所以人们知道这是正确的答案。
【解决方案2】:

在您的视图模型中使用字符串数组。然后你可以使用我一起破解的助手。如果您不想使用帮助程序和枚举,请查看底部的实际 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 />

【讨论】:

    【解决方案3】:

    已通过 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>
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-30
      • 2016-03-17
      • 1970-01-01
      相关资源
      最近更新 更多