Reputation: 13856
I am stuck up in a pretty basic page while reading form collection on post.
When I check the IsChecked checkbox, in the post action. I am getting
"true, false"
in the FormCollection. My goal is to obtain the string in below code and then parse it to boolean.
I have not idea where is the bug, can you please help?
Post Action:
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
var checkedd = collection["IsChecked"].ToString();
var name = collection["Name"].ToString();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
Model:
public class Product
{
public bool IsChecked { get; set; }
[Required]
public string Name { get; set; }
}
View:
<% using (Html.BeginForm()) { %>
<%: Html.AntiForgeryToken() %>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend>Product</legend>
<div class="editor-label">
<%: Html.LabelFor(model => model.IsChecked) %>
</div>
<div class="editor-field">
<%: Html.CheckBoxFor(model => model.IsChecked) %>
<%: Html.ValidationMessageFor(model => model.IsChecked) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.Name) %>
</div>
<div class="editor-field">
<%: Html.EditorFor(model => model.Name) %>
<%: Html.ValidationMessageFor(model => model.Name) %>
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
<% } %>
Upvotes: 0
Views: 146
Reputation:
Since you passing a model to you view, why are you using FormCollection
? if you change you POST method to
[HttpPost]
public ActionResult Create(Product model)
{
you model will be correctly bound.
The reason you are getting this value for the IsChecked
is that the CheckBoxFor
helper renders 2 controls - <input type="checkbox" ..>
and <input type="hidden" ...>
.
Because unchecked checkboxes do not post back, the 2nd hidden input ensures a value of false is posted back when its unchecked. The default model binder reads the first value matching the property name and (ignores the second if it exists).
If you really want to use FormCollection
, then don't use CheckBoxFor
- just manually include the html for a checkbox. Then if the value exists in FormCollection
, it must be true
, otherwise it must be false
Upvotes: 1