Check Uncheck CheckBox on Button Click with Button Text in ASP.Net MVC

Last Reply one month ago By chetan

Posted one month ago

I have button: Turn Email On and checkbox(which is unchecked) on side of that button.

When i click Turn email on button,it should call action method of controller where i have to write SP to update the email table.
like update tablename set isemailon_off=1 where isemailon_off=0.

Email table have one field: isemailon_off(int type).i inserted value 0 into it.

So, Turn email on button's text will become turn email off and checkbox becomes checked.

How to achieve this using Mvc?
Any help will be highly appreciated.

Turn Email ON (button) Checkbox(unchecked)
                                ||
                           BECOMES

Turn Email Off (button) Chekbox(checked)

Posted one month ago

Hi chetan,

Check this example. Now please take its reference and correct your code.

Database

CREATE TABLE EmailSubscription(Id INT IDENTITY PRIMARY KEY,isemailon_off INT)
INSERT INTO EmailSubscription VALUES(0)

Model

public class CheckUnCheckModel
{
    public string ButtonText { get; set; }
    public bool CheckUnCheck { get; set; }
}

Controller

public class HomeController : Controller
{
    // GET: /Home/
    public ActionResult Index()
    {
        CheckUnCheckModel model = BindCheckBoxButton();
        return View(model);
    }

    private static CheckUnCheckModel BindCheckBoxButton()
    {
        TestEntities entities = new TestEntities();
        EmailSubscription email = entities.EmailSubscriptions.FirstOrDefault();
        CheckUnCheckModel model = new CheckUnCheckModel();
        model.ButtonText = Convert.ToBoolean(email.isemailon_off) ? "Turn Email Off" : "Turn Email On";
        model.CheckUnCheck = Convert.ToBoolean(email.isemailon_off);
        return model;
    }

    [HttpPost]
    public ActionResult Index(string submit)
    {
        TestEntities entities = new TestEntities();
        EmailSubscription email = entities.EmailSubscriptions.FirstOrDefault();
        email.isemailon_off = submit.ToLower() == "turn email on" ? 1 : 0;
        entities.SaveChanges();
        CheckUnCheckModel model = BindCheckBoxButton();
        return View(model);
    }
}

View

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

<%@ Import Namespace="_834192_Check_UnCheck_CheckBox.Models" %>
<!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 runat="server">
    <title>Index</title>
</head>
<body>
    <%using (Html.BeginForm("Index", "Home", FormMethod.Post))
      { %>
    <input type="submit" value='<%= Model.ButtonText%>' name="submit" />
    <input name="CheckUnCheck" <%=(Convert.ToBoolean(Model.CheckUnCheck) ?  "checked='checked'" : string.Empty)%>
        type="checkbox" />
    <%} %>
</body>
</html>

Screenshot


Posted one month ago

Hi Sir,i used the Following Approach: .cshtml

<div class="col-md-8 form-group" style="text-align:right;">
    <input type="button" value="Turn Email ON" class="btn btn-success" id="btnturnemailonoff" />
</div>
<div class="col-md-2 form-group">
    <input type="checkbox" id="Chkemailonoff" />
</div>
<script type="javascript">
    $(document).ready(function () {
        $('#btnturnemailonoff').on('click', function () {
            var checked = !$(this).data('checked');
            $("#Chkemailonoff").prop('checked', checked);
            $(this).val(checked ? 'Turn Email Off' : 'Turn Email on')
            $(this).data('checked', checked);
            debugger;
            var url = '@Url.Action("CheckEmail", "BillingDetails")';
            $.ajax({
                url: url,
                type: "POST",
                data: { checkemails: checked },
                dataType: "json",
                // traditional: true,
                success: function () {
                    alert("ajax request to server succeed");
                }
            });
        });
    });
</script>

Got Struck here: Controller 

[HttpPost]
public ActionResult CheckEmail(string checkemails)
{
    //how to use SP
    return new JsonResult { };
}

 



Posted one month ago

Finally worked..:)

        <div class="col-md-8 form-group" style="text-align:right;">
            <input type="button" value="Turn Email ON" class="btn btn-success" id="btnturnemailonoff" />
        </div>
        <div class="col-md-2 form-group">
            <input type="checkbox" id="Chkemailonoff" />
        </div>
        <script type="javascript">             
            $(document).ready(function () {
                $('#btnturnemailonoff').on('click', function () {                    
                    var checked = !$(this).data('checked');
                    $("#Chkemailonoff").prop('checked', checked);
                    $(this).val(checked ? 'Turn Email Off' : 'Turn Email on')
                    $(this).data('checked', checked);
                    debugger;
                    var url = '@Url.Action("CheckEmail", "BillingDetails")';
                    $.ajax({
                        url: url,
                        type: "POST",
                        data: { checkemails: checked },
                        dataType: "json",
                        // traditional: true,
                        success: function () {
                            alert("ajax request to server succeed");
                        }
                    });
                });
            }); 
        </script>

Update model from the database...  

Controller code:

        [HttpPost]
        public ActionResult CheckEmail(string checkemails)
        {           
            //calling Stored Procedure
            if (!string.IsNullOrWhiteSpace(checkemails))
            {
                var checkemails1 = new SqlParameter("checkemails", checkemails);
                db.Database.ExecuteSqlCommand("EXEC Sp_Email_on_off @checkemails", checkemails1);
            }

            return new JsonResult { };
        }

Thank u so much Sir for the Help...highly appreciated...:)