Many times we need to pass dictionary to a controller action in Asp.Net MVC applications. For example you have list with checkboxs and you want to post the value and text of the checkboxs but in your controller you have defined a dictionary as an argument. Simply posting the values will not bind to dictionary. So before posting that value to our controller action we need to change the data structure.
Here is the controller action method that takes dictionary as parameter:
[HttpPost]
public JsonResult Example(Dictionary<int, bool> checkboxValues)
{
// Your Logic
return Json("Success", JsonRequestBehavior.AllowGet);
}
Here is the code for converting checkbox values to dictionary in javascript:
function Foo(){
var dict = new Object();
$("#ckbx table tr:gt(0)").each(
function(index, item){
checkbox = $(this).find("input:checkbox")[0];
dict["[" + index + "].Key"] = $(checkbox).prop('value');
dict["[" + index + "].Value"] = $(checkbox).prop('checked');
}
);
$.ajax({
type:'POST',
cache: false,
traditional: true,
url: '/example/example',
dataType: 'json',
data: dict,
success: function(data){
// your implementation
}
});
}
Be First to Comment