user8811
user8811

Reputation: 75

How to check if a check box is checked or not in MVC?

I have a checkbox control in a view of m MVC application. How can I check if it is checked or not in a controller? Is this possible?

Upvotes: 1

Views: 6210

Answers (1)

V2Solutions - MS Team
V2Solutions - MS Team

Reputation: 1127

You should use a Boolean value as the parameter to CheckBox to indicate the checked status and get the ids of the selected check boxes and pass to the controller

Code in View :

@model checkbox_app.Models.CheckboxModel

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>

    <script src="~/Scripts/jquery-1.8.2.min.js"></script>
    <script>
        $(document).ready(function () {

            $("#checkbox").change(function ()
            {
                var n = $(this).is(':checked');
                if ($(this).is(':checked')) {
                    $.ajax({
                        url: '@Url.Action("Index1", "Check")',
                        data: { check: n },
                        type: 'GET',
                        datatype: "json",
                        contentType: 'application/json; charset=utf-8',
                        async: false,
                        success: function (data) {
                            alert(data.results);
                        }
                    });
                }
            });            
        });
    </script>
</head>
<body>  
        <div class="editor-field fieldwidth floatL">
            @Html.CheckBoxFor(x => Model.checkCntrl, new { id = "checkbox"})
        </div> 
</body>
</html>

Code in Model :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace checkbox_app.Models
{
    public class CheckboxModel
    {
        public bool checkCntrl { get; set; }

    }
}

Code in Controller :

using checkbox_app.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace checkbox_app.Controllers
{
    public class CheckController : Controller
    {
        //
        // GET: /Check/

        public ActionResult Index()
        {

                return View();


        }

        public ActionResult Index1(bool check)
        {

            if (check)
            {
                string str = "done";
                 return Json(new { results = str }, JsonRequestBehavior.AllowGet);

            }
            else
            {
                return View("Error");
            }
        }

    }
}

Upvotes: 3

Related Questions