0

Working with a checkboxes, and stucked in transfer selected checkboxes to backend. I've an idea how to do this, but I want to hear another variants. So I've a table with checkboxes:

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

And submit button

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

So my variant is to add bool property and change table from input to @html.checkboxfor(_ => _.selected), and how then get these selected items? Is there others way how to solve this problem?

//controller logic

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.

Due to Ali sultani suggestion, here is update, but have problem, have null on from here 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>

and cs controller:

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");
    }
semper fi
  • 727
  • 3
  • 17
  • 32

3 Answers3

3

You can do like this:

View:

<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>

action:

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();
    }
Ali Soltani
  • 9,589
  • 5
  • 30
  • 55
  • check out upd 2 please – semper fi Jul 01 '16 at 10:27
  • @Vitaliy Add using (Html.BeginForm()) to view. – Ali Soltani Jul 01 '16 at 10:35
  • @Vitaliy I tested this code in my system and get selected checkboxes. I think this problem is in your view. Please update view code completely. – Ali Soltani Jul 01 '16 at 15:18
  • Updated view. Maybe should i use input type = submit with httpost attribue? I've tried it and noticed that if i'm adding attribute [HttpPost] it gives me error via '@html.actionlink' and 'input type = submit' that 'resource could not be found', if i'm removing this attribute, it works only with @html.actionlink – semper fi Jul 03 '16 at 18:15
  • When you use ActionLink, you will need to pass parameters to action in controller.You did not pass any parameters in ActionLink. – Ali Soltani Jul 03 '16 at 18:30
  • 1
    You can use input type = submit,also you should edit Html.BeginForm like this: @using (Html.BeginForm("Action name", "controller name")) – Ali Soltani Jul 03 '16 at 18:46
  • 1
    @Vitaliy please upvote and accept this answer if this answer helps you, so people know this is the correct answer. – Ali Soltani Jul 06 '16 at 18:30
  • Today have fixed this via Ajax.Begin form, will update soon solution. It is similar to your variant – semper fi Jul 06 '16 at 20:16
0

Use a string array in your view model. You can then use the helper I hacked together. if you don't want to use the helper and the enum then see the actual Html at the bottom. The binder will return a string array with only the selected string values in it. if none are selected it returns a null value for your array. You must account for that, you have been warned :)

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))

Use this if helper extensions scare you:

            <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 />
-1

Had fixed this via ajax.begin form

@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>
}
semper fi
  • 727
  • 3
  • 17
  • 32