I am working on mvc3. I have created one model which content two property i.e. Name and IsSelect.
Here it is.
public class DemoModel
{
public string Name { get; set; }
public bool? IsSelect { get; set; }
}
I am passing this model to view.
public ActionResult checkbox()
{
DemoModel model = getdemoModel();
return View(model);
}
[HttpPost]
public ActionResult checkbox(DemoModel model)
{
ModelState.Clear();
return View(model);
}
public DemoModel getdemoModel()
{
DemoModel demoModel = new DemoModel();
demoModel.Name = "ABC";
demoModel.IsSelect = null;
return demoModel;
}
Here is my view look like.
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>DemoModel</legend>
<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>
<div class="editor-label">
@Html.LabelFor(model => model.IsSelect)
</div>
<div class="editor-field">
@Html.CheckBoxFor(model => model.IsSelect.Value)
@Html.ValidationMessageFor(model => model.IsSelect)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
When I run this it gives me an error i.e. on @Html.CheckBoxFor(model => model.IsSelect.Value)
line.
Nullable object must have a value.
But when I set IsSelect value to false it works fine. But it not returns value for IsSelect property. It returns null value to controller. I think this is very simple issue but I miss something. So, How can I handle null value in @Html.CheckBoxFor? and How can I return it's value to controller?