Change Button Text and CheckBox checked unchecked based on Database value in ASP.Net MVC

Last Reply 2 months ago By dharmendr

Posted 2 months ago

Turn on email Buttton---> i am turning on the button(click)---> so button becomes Turn off button(text changed) and checkbox becomes checked.

On page Load,i am getting the same as Turn on button and unchecked checkbox. i tried by adding the Following javascript on page load but dint worked for me:

Model:

public ActionResult Index()
{
     BD.isEmailON_OFF= db.Email_ON_OFF_T.Select(x=>x.isEmailON_OFF).FirstOrDefault().GetValueOrDefault();
}

I have table:IS_Email_on_OFF_T:

I inserted to isemailonoff column as 0

Sp: 

ALTER procedure [dbo].[Sp_Email_on_off]
    @checkemails varchar(10)
As
Begin
    if(@checkemails='false')
        Update Email_ON_OFF_T set isEmailON_OFF=0
    else
        Update Email_ON_OFF_T set isEmailON_OFF=1
End

Controller:

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

            return new JsonResult { };
        }

views: 

            @{
                if (Model.isEmailON_OFF == 0)
                {
                    <input type="button" value="Turn Email on" class="btn btn-success" id="btnturnemailonoff" />
                    <input type="checkbox" id="Chkemailonoff" style="float:right;" />
                }
                else
                {
                    <input type="button" value="Turn Email off" class="btn btn-success" id="btnturnemailonoff" />
                    <input type="checkbox" id="Chkemailonoff" style="float:right;" checked/>
                }
            }

Ajax call on button click: 

<script type="text/javascript">
    $(document).ready(function () {
        $('#btnturnemailonoff').on('click', function () {
            var checked = !$(this).data('checked');
            var message = checked ? 'Turn Email ON' : 'Turn Email OFF';
            if (confirm("Do you want to " + message + "? ")) {
                $("#Chkemailonoff").prop('checked', checked);
                $(this).val(checked ? 'Turn Email Off' : 'Turn Email on')
                $(this).data('checked', checked);
                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");
                    }
                });
            }//end of if
        });
    });
</script>

This is what i tried.

turn on email----->becomes turn off button and checkebox checked.

turn off button----> becomes turn on button and checkbox uncheked.

worked correctly till here.

turn on email----->becomes turn off button and checkebox checked.

page load(loading the page)

clicking on turn off button and not changing to turn on button(1st attempt)(ISSUE)

clicking on turn off button(2nd tym) and it changes. 

You are viewing reply posted by: dharmendr 2 months ago.
Posted 2 months ago

Hi chetan,

chetan says:
var checked = !$(this).data('checked');

Your problem is with the above line of code.

When page refreshed you will always get true for data attribute.

So instead of using data attribute use the checkbox checked property to check the value and based on that update the code.

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

Here i have used entity framework to update the record in database. You need to change with your stored procedure code.

Database

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

Controller 

public class HomeController : Controller
{
    // GET: /Home/
    public ActionResult Index()
    {
        TestEntities db = new TestEntities();
        return View(db.EmailSubscriptions.FirstOrDefault());
    }

    [HttpPost]
    public ActionResult CheckEmail(string checkemails)
    {
        if (!string.IsNullOrWhiteSpace(checkemails) || checkemails == "true" || checkemails == "false")
        {
            TestEntities db = new TestEntities();
            int status = 0;
            if (checkemails.ToLower() == "true")
            {
                status = 1;
            }
            EmailSubscription email = db.EmailSubscriptions.FirstOrDefault();
            email.isemailon_off = status;
            db.SaveChanges();
        }

        return new JsonResult { };
    }
}

View

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

<!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>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('#btnturnemailonoff').on('click', function () {
                var checked = $("#Chkemailonoff").prop('checked');
                var message = checked ? 'Turn Email On' : 'Turn Email Off';
                if (confirm("Do you want to " + message + "? ")) {
                    $("#Chkemailonoff").prop('checked', !checked);
                    $(this).val(message)
                    $.ajax({
                        url: 'Home/CheckEmail',
                        type: "POST",
                        data: { checkemails: !checked },
                        dataType: "json",
                        success: function () {
                            //alert("ajax request to server succeed");
                        }
                    });
                } //end of if
            });
        });
    </script>
</head>
<body>
    <%if (Model.isemailon_off == 0) {%>
    <input type="button" value="Turn Email On" id="btnturnemailonoff" />
    <input type="checkbox" id="Chkemailonoff" />
    <%} else {%>
    <input type="button" value="Turn Email Off" id="btnturnemailonoff" />
    <input type="checkbox" id="Chkemailonoff" checked />
    <%} %>
</body>
</html>

Screenshot