Niranjan Godbole
Niranjan Godbole

Reputation: 2175

How to get viewbag data in jquery?

Hi I am developing web application in mvc5. I have login form with username and password fields as below.

@using (Html.BeginForm("ClickAction", "Login", FormMethod.Post))
{
           @Html.TextBox("txtUid", null, new { @maxlength = "15", id = "txtUid",  
           @class = "form-control validate[requiredInLogin] text-input "})
           @Html.Password("txtPassword", null, new { @maxlength = "15", id = 
           "txtPassword", @class = "form-control validate[requiredOutLogin] text-input" })
           <input type="submit" class="btn btn-primary btnLogin red" 
           value="SIGN IN" name="submit" />
}

I have below action method,

  [HttpPost]
        public ActionResult ClickAction()
        { 
         //Some logic
         //When 3 unsuccessful attempts made to login then i set
         //ViewBag.captcha = true; 
         return View();
        }

I will make 3 unsuccessful attempts to login then i will set ViewBag.captcha to true. Once i set ViewBag.captcha to true i want to access the ViewBag.captcha value in View and i want to display captcha. May i know how can i access Viewbag value in view? any help would be appreciated. Thanks,

Meanwhile i tried below options,

@{
    var message = ViewBag.captcha;
}

Then in JS

var message = '@message';
if (message)
{
alert(message);
}

Below is my login view.

<html>
<head></head>
<body>
    <div id="formID">
        @*<form id="formID">*@
        <div class="loginContainer">
            <div class="loginContentArea">
                <div class="loginLogo"><img src="~/images/c3card.png" alt="C3 Card"  align="middle" /></div>
                @using (Html.BeginForm("ClickAction", "Login", FormMethod.Post))
                {
                    <div class="loginUsernamePassword">
                        <i class="fa fa-user"></i>
                        @Html.TextBox("txtUid", null, new { @maxlength = "15", id = "txtUid",  @class = "form-control validate[requiredInLogin] text-input ", placeholder = "Username", autocomplete = "off" })
                    </div>
                    <div class="loginUsernamePassword">
                        <i class="fa fa-lock"></i>
                        @Html.Password("txtPassword", null, new { @maxlength = "15", id = "txtPassword", @class = "form-control validate[requiredOutLogin] text-input", placeholder = "Password", autocomplete = "off", Style = "background:#FFFFFF;" })
                   </div>
                    <div class="errormessage">@TempData["Message"]</div>
                    <div class="captcha" id="captcha">
                        <div class="g-recaptcha" data-badge="inline" data-sitekey=@System.Configuration.ConfigurationManager.AppSettings["recaptchaPublicKey"]></div>
                        <br />
                    </div>
                        <div class="loginButton">
                            <input type="submit" class="btn btn-primary btnLogin red" value="SIGN IN" name="submit" />
                        </div>
                        <div class="loginLink">@Html.ActionLink("Forgot Your Password?", "Index", "ForgotPassword")@*<a href="#" data-featherlight="#recoverpwd"></a>*@</div>
                        }

                    </div>
        </div>
    </div>
    <script type="text/javascript">
        $(function () {
            $('input[type=password]').each(function () {
               $(this).attr('data-background-color', $(this).css('background-color'));
               $(this).css('background-color', $(this).css('color'));
                $(this).attr('type', 'text');
                $(this).focus(function () {
                    $(this).attr('type', 'password');
                    $(this).css('background-color', $(this).attr('data-background-color'));
                });

                $(this).blur(function () {
                    $(this).css('background-color', $(this).css('color'));
                    $(this).attr('type', 'text');
                });
            });
        });
        jQuery(document).ready(function () {
            @{ var message = ViewBag.captcha; }
            alert(message);
            if (message) { alert(message); }

            $("[id=captcha]").hide();
            // binds form submission and fields to the validation engine
            jQuery("#formID").validationEngine();
            $("formID").attr('autocomplete', 'off');
            $('#txtUid').attr('autocomplete', 'off');

            $('#txtPassword').attr('autocomplete', 'off');
        });
        $("#myinput").rules("add", {
            minlength: 2
        });
    </script>

</body>
</html>

This does not work for me.

May i know proper way to access viewbag value in the above scenario? Any help greatly appreciated. Thank you so much.

Upvotes: 2

Views: 10889

Answers (3)

Anastasios Selmani
Anastasios Selmani

Reputation: 3699

Since you are using Razor you could do this: 1. Get your ViewBag value to a variable

<script type="text/javascript">
    var message = "@ViewBag.captcha";
</script>

You don't have to set it inside your document ready. 2.The variable is of type string however. In order to use it in a function you will have to do something like that:

If(message.toLowerCase() == "true")

in order to get the desired effect.

To convert it to boolean you could use something like that

message = message.toLowerCase() === "true"

Hope it helps

Upvotes: 3

Lajos Arpad
Lajos Arpad

Reputation: 76551

You can initialize a ViewBag value like this:

ViewBag.captcha = "true";

Then you can access it like this in a view:

var message = @ViewBag.captcha;

From here on you will be able to use message. What you essentially did was the following:

  • you initialize ViewBag.captcha (note that this part is commented out)
  • you put that into a variable called message
  • you try to get @message as a string, but you are not using the Javascript value calculated

Upvotes: 2

Niladri
Niladri

Reputation: 5962

Can you change the message variable like below in JS and then try

jQuery(document).ready(function () {
        var message = '@ViewBag.captcha'; //change it here
        if (message)
        {
          alert(message);
        }
        $("[id=captcha]").hide();
        // binds form submission and fields to the validation engine
        jQuery("#formID").validationEngine();
        $("formID").attr('autocomplete', 'off');
        $('#txtUid').attr('autocomplete', 'off');

        $('#txtPassword').attr('autocomplete', 'off');
    });  

Upvotes: 1

Related Questions