checkbox returning "true,false" from formcollection instead of selected value
Solution 1
You could always try this:
bool checkedValue = Form["checkbox0"].Contains("true");
Solution 2
Try like this:
$.ajax({
type: 'POST',
url: '/Home/Post',
data: $('form').serialize(),
dataType: 'json',
success: function () {
},
});
And also I would recommend you using a view model:
[HttpPost]
public ActionResult Post(MyViewModel model)
{
...
}
where for example you have a list of values:
public class MyViewModel
{
public ItemViewModel[] Items { get; set; }
}
public class ItemViewModel
{
public int Id { get; set; }
public bool IsSelected { get; set; }
}
and for which you generated a list of checkboxes in your strongly typed view:
<% for (var i = 0; i < Model.Items.Length; i++) { %>
<%= Html.HiddenFor(x => x.Items[i].Id) %>
<%= Html.CheckBoxFor(x => x.Items[i].IsSelected) %>
<% } %>
Solution 3
Try this
string abc = ((string[])(collection.GetValue("checkbox0").RawValue))[0];
shiv455
Updated on July 22, 2022Comments
-
shiv455 almost 2 years
im having multiple checkboxes in my aspx page using HtmlHelper.CheckBox
and when the form is submitted using ajax as below in js file
var input = $(':input');
$.ajax({ type: 'POST', url: "/Home/Post", data: input, dataType: 'json', success: function () { }, });
and in the controller action method as shown below..
public ActionResult Post(FormCollection Form) { }
and in the Form im not getting the updated values for checkboxes ie all the checkbox values were returned as "true,false". if any of the checkbox is not checked or unchecked...Form is not returning as false it still returns as "true,false" instead of false.
even i tried as
Form.Get("checkbox0").ConvertTo(typeof(Boolean)) Request.Form["checkbox0"]
the aboce code returns "true,false" but the checkbox0 is unchecked so it should return false which is not happening....???
But when i tried using
Html.BeginForm("Post","Home",FormMethod.Post,new {id="x"})
in aspx file and removed ajax call in the js file... then the formcollection in the controller start giving me the expected values for checkboxes... but as this approach flickers page after page submit...i need to use ajax approach only..Please let me know how can i retrieve the updated value of the checkbox from the formcollection when using ajax.