I want to test if the checkbox is checked or not from my action method, what i need is to pass checkbox value from view to controller.
This is my view:
For some reason Andrew method of creating the checkbox by hand didn't work for me using Mvc 5. Instead I used this
@Html.CheckBox("checkResp")
to create a checkbox that would play nice with the controller.
public ActionResult Save(Director director)
{
// IsActive my model property same name give in cshtml
//IsActive <input type="checkbox" id="IsActive" checked="checked" value="true" name="IsActive"
if(ModelState.IsValid)
{
DirectorVM ODirectorVM = new DirectorVM();
ODirectorVM.SaveData(director);
return RedirectToAction("Display");
}
return RedirectToAction("Add");
}
<form action="Save" method="post">
IsActive <input type="checkbox" id="IsActive" checked="checked" value="true" name="IsActive" />
</form>
public ActionResult Save(Director director)
{
// IsValid is my Director prop same name give
if(ModelState.IsValid)
{
DirectorVM ODirectorVM = new DirectorVM();
ODirectorVM.SaveData(director);
return RedirectToAction("Display");
}
return RedirectToAction("Add");
}
For the MVC Controller method, use a nullable boolean type:
public ActionResult Index( string responsables, bool? checkResp) { etc. }
Then if the check box is checked, checkResp will be true. If not, it will be null.
try using form collection
<input id="responsable" value="True" name="checkResp" type="checkbox" />
[HttpPost]
public ActionResult Index(FormCollection collection)
{
if(!string.IsNullOrEmpty(collection["checkResp"])
{
string checkResp=collection["checkResp"];
bool checkRespB=Convert.ToBoolean(checkResp);
}
}
set value in check box like this :
<input id="responsable" name="checkResp" value="true" type="checkbox" />
change checkResp to nullable property in Your model like this :
public Nullable<bool> checkResp{ get; set; }
use ? before checkResp like :
public ActionResult Index( string responsables, bool ? checkResp)
{
......
}