Archive

Posts Tagged ‘mvc3 pagedlist checkbox state’

Preserving Check Box States PagedList MVC3

January 9, 2014 Leave a comment

🙂 It can be done using a session variable.

Using the following javascript snippet we can get the coma seperated selected and deselected check box ids on paging

var searchSelectedIDs = $("#table1 input:checkbox:checked").map(function ()
{
return $(this).val();
}).get()
var searchDeSelectedIDs = $("#table1 input:checkbox:not(:checked)").map(function ()
{
return $(this).val();
}).get()
$.ajax({
url: '/Utility/SaveContactIDs?SelectedIDs=' + searchSelectedIDs +'&DeSelectedIDs='+searchDeSelectedIDs,
type: 'GET',
cache: false,
success: function (result) {
},
error: function (p, s, r) {    }
});

In the controller

public string SaveContactIDs(string SelectedIDs, string DeSelectedIDs)
{

string contactSearch = Convert.ToString(Session["ContactSearchIDs"]);

if (contactSearch != "")
{
string[] sIds = SelectedIDs.Split(',');

foreach (string str in sIds)
{
if (!contactSearch.Split(',').Contains(str))
{
Session["ContactSearchIDs"] = Session["ContactSearchIDs"] + str + ",";
}

}


}
else
{
Session["ContactSearchIDs"] = SelectedIDs + ",";
}

string[] deselectedValues = DeSelectedIDs.Split(',');
string ids = Convert.ToString(Session["ContactSearchIDs"]);
foreach (string str in deselectedValues)
{
if (str.Trim() != "")
{
if (ids.Split(',').Contains(str))
{
ids = ids.Remove(ids.IndexOf(str), str.Length + 1);
}
}

}



Session["ContactSearchIDs"] = ids;

return "success";
}



in cshtml to show check box state true or false based on session value

@if(Session["ContactSearchIDs"] != null)
{

if (Convert.ToString(Session["ContactSearchIDs"]).Split(',').Contains(item.CONTACT_ID.ToString()))
{

@Html.CheckBox(item.CONTACT_ID.ToString(), true, new { @id = item.CONTACT_ID, @name = "chkSelect[]", @value = item.CONTACT_ID.ToString() })
}
else
{
@Html.CheckBox(item.CONTACT_ID.ToString(), false, new { @id = item.CONTACT_ID, @name = "chkSelect[]", @value = item.CONTACT_ID.ToString() })

}

}
else
{
@Html.CheckBox(item.CONTACT_ID.ToString(), false, new { @id = item.CONTACT_ID, @name = "chkSelect[]", @value = item.CONTACT_ID.ToString() })

}

Happy coding 🙂

 

Advertisements