How to Get Checked Property of CheckBox in MVC

Create a View with Checkbox.aspx Page.

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<MVCTEST1.Models.CheckboxModel>" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head id="Head1" runat="server">

    <title>Checkbox</title>

    <style type="text/css">

        .style1

        {

            width: 100%;

        }

    </style>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <table class="style1">

            <tr>

                <td>

                    your Options<br />

                    <%= Html.CheckBox("checkBoxID1")%>

                </td>

                <td>

                    <input type="submit" value="result" />

                </td>

            </tr>

            <tr>

                <td>

                    <%= Html.CheckBox("checkBoxID2")%>

                </td>

                <td>

                    <%: ViewData["MSG"] %>

                </td>

            </tr>

        </table>

    </div>

    </form>

</body>

</html>

Create Model as following :

#region checkbox model

public class CheckboxModel

{

public string checkBoxID1 { get; set; }

public string checkBoxID2 { get; set; }

 

}

#endregion

Create Controller as given in code..

#region For CheckBox Page

public ActionResult Checkbox()

{

return View();

}

public IList<CheckboxModel> Options { get; set; }

 

[HttpPost]

public ActionResult Checkbox(CheckboxModel ck)

{

if(!ModelState.IsValid)

{

return View("Checkbox", ck);

}

else{

 

if ((ck.checkBoxID1.ToString() == "true"))

{

if ((ck.checkBoxID2.ToString() != "true"))

{

ViewData["MSG"] = " Option 1 Selected";

}

else

{

ViewData["MSG"] = "Both Options Selected";

}

}

else

{

if ((ck.checkBoxID2.ToString() == "true"))

{

ViewData["MSG"] = "Checked Option 2";

}

else

{

ViewData["MSG"] = "No Option Selected!!!";

}

}

return View("Checkbox", ck);

}

}

#endregion

Run and click on button after selectin checkbox and see results.

Ebook Download
View all
Learn
View all