如何在jquery中获取viewbag数据?

时间:2017-09-29 10:46:25

标签: javascript c# jquery asp.net-mvc-4

您好我正在开发mvc5中的Web应用程序。我的登录表单包含用户名和密码字段,如下所示。

@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" />
}

我有以下行动方法,

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

我将尝试3次登录失败,然后我将ViewBag.captcha设置为true。一旦我将ViewBag.captcha设置为true,我想在View中访问ViewBag.captcha值,我想显示验证码。我可以知道如何在视图中访问Viewbag值吗?任何帮助,将不胜感激。谢谢,

与此同时,我尝试了以下选项,

@{
    var message = ViewBag.captcha;
}

然后在JS

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

以下是我的登录视图。

<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>

这对我不起作用。

我是否知道在上述场景中访问viewbag值的正确方法?任何帮助非常感谢。非常感谢。

3 个答案:

答案 0 :(得分:2)

您可以像这样初始化#!/bin/sh # iOS universal library build script supporting swift modules inclusive simulator slices # prevention from running xcodebuild in a recusive way if [ "true" == ${ALREADYINVOKED:-false} ]; then echo "RECURSION: Detected, stopping" else export ALREADYINVOKED="true" # output directory for universal framework UNIVERSAL_OUTPUTFOLDER=${BUILD_DIR}/${CONFIGURATION}-universal mkdir -p "${UNIVERSAL_OUTPUTFOLDER}/iOS" # build both device and simulator versions for iOS xcodebuild -project "${PROJECT_NAME}.xcodeproj" -scheme "${PROJECT_NAME}" -sdk iphonesimulator -destination 'platform=iOS Simulator,name=iPhone 8' ONLY_ACTIVE_ARCH=NO clean build xcodebuild -project "${PROJECT_NAME}.xcodeproj" -scheme "${PROJECT_NAME}" -sdk iphoneos ONLY_ACTIVE_ARCH=NO clean build # copy the framework structure from iphoneos build to the universal folder cp -R "${BUILD_DIR}/${CONFIGURATION}-iphoneos/${PROJECT_NAME}.framework" "${UNIVERSAL_OUTPUTFOLDER}/iOS" # copy existing Swift modules from iphonesimulator build to the universal framework directory SIMULATOR_SWIFT_MODULES_DIR="${BUILD_DIR}/${CONFIGURATION}-iphonesimulator/${PROJECT_NAME}.framework/Modules/${PROJECT_NAME}.swiftmodule/" if [ -d "${SIMULATOR_SWIFT_MODULES_DIR}" ]; then cp -R "${SIMULATOR_SWIFT_MODULES_DIR}" "${UNIVERSAL_OUTPUTFOLDER}/iOS/${PROJECT_NAME}.framework/Modules/${PROJECT_NAME}.swiftmodule" fi # create universal binary file using lipo and place the combined executable in the universal framework directory lipo -create -output "${UNIVERSAL_OUTPUTFOLDER}/iOS/${PROJECT_NAME}.framework/${PROJECT_NAME}" "${BUILD_DIR}/${CONFIGURATION}-iphonesimulator/${PROJECT_NAME}.framework/${PROJECT_NAME}" "${BUILD_DIR}/${CONFIGURATION}-iphoneos/${PROJECT_NAME}.framework/${PROJECT_NAME}" # intermediate step for copying the framework to the project's directory mkdir -p "${TMPDIR}/${PROJECT_NAME}/Frameworks/iOS" cp -R "${UNIVERSAL_OUTPUTFOLDER}/iOS/${PROJECT_NAME}.framework" "${TMPDIR}/${PROJECT_NAME}/Frameworks/iOS" # create a zip file and move it to the project's directory cd "${TMPDIR}/${PROJECT_NAME}/Frameworks/iOS" zip -r "${PROJECT_NAME}.framework.zip" "${PROJECT_NAME}.framework" mkdir -p "${PROJECT_DIR}/universal-framework" mv "${PROJECT_NAME}.framework.zip" "${PROJECT_DIR}/universal-framework" # optional: show the project's directory in Finder open "${PROJECT_DIR}/universal-framework" fi 值:

ViewBag

然后你可以在视图中这样访问它:

ViewBag.captcha = "true";

从这里开始,您将能够使用var message = @ViewBag.captcha; 。你基本上做的是以下几点:

  • 您初始化message(请注意,此部分已注释掉)
  • 您将其放入名为ViewBag.captcha
  • 的变量中
  • 您尝试将message作为@message,但您未使用计算的Javascript值

答案 1 :(得分:2)

由于您使用Razor,您可以这样做: 1.将ViewBag值变为变量

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

您不必在文档中准备好它。 2.变量是string类型。为了在函数中使用它,你必须做类似的事情:

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

以获得理想的效果。

要将其转换为布尔值,您可以使用类似

的内容
message = message.toLowerCase() === "true"

希望有所帮助

答案 2 :(得分:1)

您可以在JS中更改消息变量,然后尝试

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');
    });