簡體   English   中英

reCAPTCHA在MVC局部視圖頁面中不可見

[英]reCAPTCHA not visible in a MVC partialview page

我在將google reCAPTCHA添加到我的頁面時遇到了麻煩。 在版式中,我添加了Google Recaptcha js

_布局

     <title>@ViewBag.Title</title>
        @Styles.Render("~/Content/css")
        @Scripts.Render("~/bundles/modernizr")
        @Scripts.Render("~/bundles/jquery")
        @Scripts.Render("~/bundles/bootstrap")
        @RenderSection("scripts", required: false)
        <script src='https://www.google.com/recaptcha/api.js'></script>
        <script type="text/javascript">
    <script type="text/javascript">

        $(document).ready(function () {

            $('#subject').on("change", function (e) {
                e.preventDefault();
                var selectedVal = $('#subject').val();
                $.ajax({
                    //  url: "/ContactUs/GetForm",
                    url: '@Url.Action("GetForm", "ContactUs")',
                    type: "POST",
                    data: { searchValue: selectedVal } ,
                    async: true,
                    success: function (data) {
                        $('#renderForms').empty();
                        $('#renderForms').append(data);

                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        alert("An error has occured!!! " + xhr.status + " && " + xhr.responseText);
                    }
                });
            });
 });

    </script>

然后在索引中選擇要顯示的表格:

@Html.DropDownListFor(model => model.contactSelectListItems, new List<SelectListItem>
            {
                                new SelectListItem() {Text = "option1", Value="option1"},
                                new SelectListItem() {Text = "option2", Value="option2"},
                                new SelectListItem() {Text = "option3", Value="option3"},

            }, "--Choose--", new { id = "subject", @class= "dropdown-item" })
    </div>
    <div id="renderForms">
    </div>

在這兩個部分頁面中,都有一種形式,我在其中做類似但不同的viewmodel:

    @using (Html.BeginForm("SendCustomerTeam", "ContactUs", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>CustomerTeamViewModel</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="container">
    <div class="form-group form-group-sm col-sm-6">
                    <div class="row">

                        @Html.LabelFor(model => model.Phone, htmlAttributes: new { @class = "control-label col-md-2" })
                        <div class="col-sm-9">
                            @Html.EditorFor(model => model.Phone, new { htmlAttributes = new { @class = "form-control" } })
                            @Html.ValidationMessageFor(model => model.Phone, "", new { @class = "text-danger" })
                        </div>
                    </div>
                </div>
                <div class="form-group form-group-sm col-sm-12">
                    <div class="row">
                        @Html.LabelFor(model => model.Inquiry, htmlAttributes: new { @class = "control-label col-md-2" })
                        <div class="col-sm-12">
                            @Html.EditorFor(model => model.Inquiry, new { htmlAttributes = new { @class = "form-control" } })
                            @Html.ValidationMessageFor(model => model.Inquiry, "", new { @class = "text-danger" })
                        </div>
                    </div>
                </div>

                <div class="form-group form-group-sm col-sm-12">
                    <div class="row">
                        <div class="col-sm-12">
                            <div id="NotRobot">
                                <label>Are you Human?</label>                                
                                <div id='recaptcha' class="col-sm-12 g-recaptcha" 
                                     data-sitekey="@System.Configuration.ConfigurationManager.AppSettings["RecaptchaPublicKey"]"
                                     >
                                </div>
                                <div id="recaptchaMessage" data-verifyrecaptchatokenurl="@Url.Action("VerifyReCaptchaToken", "Home")" style="display:none;padding:10px;color:red;font-weight:bold;" class="error">You need to verify reCAPTCHA.</div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="form-group form-group-sm col-sm-6">
                    <div class="row">
                        <div class="col-sm-9">
                            <input id="Send" type="submit" value="Send" class="btn btn-default" />
                        </div>
                    </div>
                </div> etc...

在我的控制器中,我像這樣處理它,我想將reCAPTCHA作為ajax調用來處理,但我還沒有弄清楚該如何做。

public ActionResult Index()
        {
            ViewData["ReCaptchaKey"] = System.Configuration.ConfigurationManager.AppSettings["RecaptchaPublicKey"];
//do something here
    }
    public static bool ReCaptchaPassed(string gRecaptchaResponse, string secret)
            {
                HttpClient httpClient = new HttpClient();
                var res = httpClient.GetAsync($"https://www.google.com/recaptcha/api/siteverify?secret={secret}&response={gRecaptchaResponse}").Result;
                if (res.StatusCode != HttpStatusCode.OK)
                {
                    //logger.LogError("Error while sending request to ReCaptcha");
                    return false;
                }

                string JSONres = res.Content.ReadAsStringAsync().Result;
                dynamic JSONdata = JObject.Parse(JSONres);
                if (JSONdata.success != "true")
                {
                    return false;
                }

                return true;
            }
    [HttpPost]
            public ActionResult SendCustomerTeam(CustomerTeamViewModel model)
            {
                ContactViewModel contactModel = new ContactViewModel();
                contactModel.CustomerTeamModel = model;
                ViewData["ReCaptchaKey"] = System.Configuration.ConfigurationManager.AppSettings["RecaptchaPublicKey"];

                if (ModelState.IsValid)
                {
                    if (!ReCaptchaPassed(
                        Request.Form["g-recaptcha-response"], // that's how you get it from the Request object
                        System.Configuration.ConfigurationManager.AppSettings["RecaptchaPrivateKey"]
                        ))
                    {
                        ModelState.AddModelError(string.Empty, "You failed the CAPTCHA, stupid robot. Go play some 1x1 on SFs instead.");
                        return View(contactModel);
                    }
                }

我的問題是reCAPTCHA永遠不會出現在我的頁面上。

編輯:

我嘗試了以下簡化,以查看是否可以找到問題。

SimplePageViewModel

  public class simplePageViewModel
    {
        public string Name { get; set; }
    }

SimplePagePartialView

    @model Contact_Portal.Models.simplePageViewModel

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>simplePageViewModel</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="container">
            <div class="row">
                <div class="form-group form-group-sm col-sm-6">
                    <div class="row">
                        @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
                        <div class="col-sm-9">
                            @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                            @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
                        </div>
                    </div>
                </div>
                <div class="form-group form-group-sm col-sm-12">
                    <div class="row">
                        <div class="col-sm-12">
                            <div id="NotRobot">
                                <label>Are you Human?</label>
                                <div id='recaptcha' class="col-sm-12 g-recaptcha" style="padding:10px;"
                                     data-sitekey="@System.Configuration.ConfigurationManager.AppSettings["RecaptchaPublicKey"]">
                                </div>
                                <div id="recaptchaMessage" data-verifyrecaptchatokenurl="@Url.Action("VerifyReCaptchaToken", "Home")" style="display:none;padding:10px;color:red;font-weight:bold;" class="error">You need to verify reCAPTCHA.</div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-md-offset-2 col-md-10">
                        <input type="submit" value="Save" class="btn btn-default" />
                    </div>
                </div>
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

在控制器中,我通過此行顯示了局部視圖

return PartialView("View", contactModel.simplePageModel);

仍然存在相同的問題。

難道是因為我正在顯示包含reCAPTCHA的部分頁面作為Jquery Ajax調用的一部分? 像這樣:

  $(document).ready(function () {

        $('#subject').on("change", function (e) {
            e.preventDefault();
            var selectedVal = $('#subject').val();
            $.ajax({
                //  url: "/ContactUs/GetForm",
                url: '@Url.Action("GetForm", "ContactUs")',
                type: "POST",
                data: { searchValue: selectedVal } ,
                async: true,
                success: function (data) {
                    $('#renderForms').empty();
                    $('#renderForms').append(data);

                },
                error: function (xhr, ajaxOptions, thrownError) {
                    alert("An error has occured!!! " + xhr.status + " && " + xhr.responseText);
                }
            });
        });

現在,我嘗試了一個全新的項目,將其簡化為一個html文件:

Index.cshtml

    <!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    <link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />
    <script src="~/Scripts/modernizr-2.6.2.js"></script>
    <script src='https://www.google.com/recaptcha/api.js'></script>
</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                </ul>
            </div>
        </div>
    </div>

    <div class="container body-content">
        <div id='recaptcha' class="col-sm-12 g-recaptcha" style="padding:10px;"
             data-sitekey="@System.Configuration.ConfigurationManager.AppSettings["RecaptchaPublicKey"]"></div>
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>

    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script src="~/Scripts/bootstrap.min.js"></script>
</body>
</html>

仍然不可見,它永遠不會出現。 為什么它不起作用? Google的Recaptcha不支持ASP.NET MVC嗎?

您的腳本src錯誤:

<script src='https://www.google.com/recaptcha/api.js async defer'></script>

<script src='https://www.google.com/recaptcha/api.js'></script>

還可以檢查deveoper控制台,如果有任何錯誤?

好吧,我找到了一個我不滿意的解決方案,但是它可行。

在我的布局文件中,我做了如下部分:

 <script src="https://www.google.com/recaptcha/api.js" async defer></script>
 <script type="text/javascript">
     function enableBtn() {
                document.getElementById("subject").disabled = false;
            }
     $(document).ready(function () {
         document.getElementById("subject").disabled = true;
      });

    </script>

然后在我看來,我創建了這個

<div class="g-recaptcha" data-sitekey="*********PublicKEY*************" data-callback="enableBtn"></div>

它似乎正在工作。

我希望我可以使其在局部視圖中起作用,因為現在無論其他情況如何,我都必須擁有它,而不僅僅是提交。

我不知道我是否可以再驗證這一服務器端,因為它也在我的表單之外。 任何有更好選擇的人都會受到歡迎。

編輯:

我找到了一個更好的解決方案。 我這樣更改了ajax調用:

 $('#subject').on("change", function (e) {
                e.preventDefault();
                var selectedVal = $('#subject').val();
                $.ajax({
                    //  url: "/ContactUs/GetForm",
                    url: '@Url.Action("GetForm", "ContactUs")',
                    type: "POST",
                    data: { searchValue: selectedVal } ,
                    async: true,
                    success: function (data) {
                        $('#renderForms').empty();
                        $('#renderForms').append(data);

                        if (!debug) {
                            document.getElementById("Send").disabled = true;
                            grecaptcha.render('Captcha', {
                                'sitekey': '**********PublicKey*********',
                                'callback': function() {
                                    document.getElementById("Send").disabled = false;
                                },
                                'expired-callback': function() {
                                    //document.getElementById("subject").selectedIndex = 0;
                                    document.getElementById("Send").disabled = true;
                                    //document.getElementById("renderForms").innerHTML = "";
                                }


                            });

                        }
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        alert("An error has occured!!! " + xhr.status + " && " + xhr.responseText);
                    }
                });
            });

現在它正在按我的預期工作。 至少在用戶界面部分。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM