Send Checked CheckBox values as Comma Separated String to another View using Query String in ASP.Net MVC

Last Reply 7 days ago By dharmendr

Posted 7 days ago

hello,

i am using this snippet

Save (Insert) multiple CheckBoxes (CheckBoxList) values to database in ASP.Net MVC

i want on each checkbox change even it should take the value of checkbox list to query string as comma seperated like

abc.com?checkboxaluve= apple, fruit, 

so pass each selected checkbox value as comma seperated to query sting

Posted 7 days ago

Hi nauna,

Using the article i have created the example.

Save (Insert) multiple CheckBoxes (CheckBoxList) values to database in ASP.Net MVC

Check this example. Now please take its reference and correct your code.

Controller

public class HomeController : Controller
{
    // GET: /Home/
    public ActionResult Index()
    {
        HobbiesEntities entities = new HobbiesEntities();
        return View(entities.Hobbies.ToList());
    }

    public ActionResult Details(string checkboxaluve)
    {
        TempData["Hobbies"] = checkboxaluve;
        return View();
    }
}

View

Index

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<IEnumerable<_168965_Checked_CheckBox_QueryString_MVC.Hobby>>" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Index</title>
    <script type="text/javascript" src="https://code.jquery.com/jquery-2.2.3.js"></script>
    <script type="text/javascript">
        $(function () {
            $('.Save').on("click", function () {
                var hobbies = "";
                $("#tblHobbies input[type=checkbox]:checked").each(function (index, item) {
                    hobbies += $(item).closest('tr').find('td').eq(1).text().trim() + ",";
                });
                var url = $(this).attr('href') + '?checkboxaluve=' + hobbies;
                location.href = url;
                return false;
            });
        });
    </script>
</head>
<body>
    <table id="tblHobbies">
        <% foreach (var item in Model)
           { %>
        <tr>
            <td>
                <%:Html.CheckBoxFor(m=>item.IsSelected)%>
            </td>
            <td>
                <%:Html.DisplayFor(m => item.Hobby1)%>
                <%:Html.HiddenFor(m => item.HobbyId)%>
            </td>
        </tr>
        <% } %>
    </table>
    <br />
    <%:Html.ActionLink("Send", "Details", "Home", new { }, new { @class = "Save" })%>
</body>
</html>

Details

Hobbies : <%=TempData["Hobbies"]%><br />
<%:Html.ActionLink("Back", "Index", "Home")%>

Screenshot