Reputation: 175
I have a checkbox:
<form action="" method="POST">
<label>
Archived
@Html.CheckBox("checkedArchive")
</label>
</form>
When it's checked, I want it to call the ContentResult which has a number of methods in place with an additional new value to check whether it was checked/unchecked:
public ContentResult Data(int? id)
So far, I have:
[HttpPost]
public ActionResult Index(FormCollection formData)
{
bool checked;
//Check if value is selected and set bool to true or false
return RedirectToAction("Data", new {checked});
}
But I'm unable to do any checking and passing. There must be a simpler way.
Upvotes: 0
Views: 5554
Reputation: 1058
Without submitting the form, you can make the ajax request and send the checkbox's values as parameter.
After sending this value to the controller you can determine the value in the parameter, And call your required method against the value.
Upvotes: 0
Reputation:
If it is possible to change the signature of your index like this:
[HttpPost]
public ActionResult Index(FormCollection formData, bool? checkedArchive)
{
bool checked;
if(!checkedArchive.HasValue)
checked = false;
else
checked = checkedArchive.Value;
//Check if value is selected and set bool to true or false
return RedirectToAction("Data", new {checked});
}
I hope it will help. Note that this solution will work if you have a submit button
. What you trying to achieve I think you need to use a Jquery Ajax function attached to the event change of your
checkbox` and call the appropriate action in your controller.
First you need to reference the JQuery lib in your view and then put this script in the head in the head
$(document).ready(function() {
$("#HcheckedArchiven").click(function(){
$.ajax({
url: '@Url.Action("actionmethod", "controllername")',
type: "POST",
data: //data,
dataType: //type of response,
success: function (data) {
//your code here
}
error: function(data){
}
});});
})
Also that if you want to call ajax not on click but only if value is checked or not then you must use an if condition in the click event to check the same using $(this).is(:checked)
Upvotes: 0
Reputation: 277
bool checked=Request.Form.AllKeys.Where(c => c.Contains("checkedArchive")).FirstOrDefault() != null;
Since only the checked values will be posted back you don't need to validate that they're checked.
Upvotes: 1
Reputation: 23113
I check for generic checkboxes the following way:
bool checked = Request.Form["checkedArchive"] != "false";
Upvotes: 0