简体   繁体   English

为什么在“剃刀”页面上无法获得正确的文本框值?

[英]Why can't I get the correct textbox value on Razor page?

This is simple webpage with textbox and alert box to show its value on a razor view page: 这是带有文本框和警报框的简单网页,可在剃刀视图页面上显示其值:

<!DOCTYPE html>
<html>
    <head>
        <title>Demo</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
    </head>
    <body>
        @using (Html.BeginForm())
        {
            <div>
                @Html.Label("Enter your name")   
                @Html.TextBox("txtName")
            </div>  
            <input type="button" id="btnPost" value="Load Data using Post" />

            <script>
                $(document).ready(function () {
                    //$("#txtName").keyup(function () {
                    //    alert(this.value);
                    //});
                    var originvalue = $("#txtName").val();

                    $("#btnPost").click(function () {
                        alert(originvalue);
                    });
                });
                });
            </script>
        }
    </body>
</html>

I have taken the textbox value and assigned it to a var originvalue . 我已经获取了文本框值并将其分配给var originvalue Now I want to show this value in an alert box. 现在,我想在警报框中显示此值。 Is this some kind of bug? 这是某种错误吗? I can't figure out what is missing here. 我不知道这里缺少什么。

The problem is because you only set originvalue when the page loads and the input has no value in it. 问题是因为仅在页面加载且input中没有值时才设置originvalue If you want to retrieve the value the user typed, set that variable inside the click handler: 如果你想获取用户输入的值时,设置的点击处理程序内部的变量:

$(document).ready(function () {
    $("#btnPost").click(function () {
        var originvalue = $("#txtName").val();
        console.log(originvalue);
    });
});

Also note that your original JS code has one set of closing braces/brackets too many, and you should also use console.log() to debug over alert() because the former does not coerce data types. 还要注意,您的原始JS代码中有一组右括号/括号太多,并且您还应该使用console.log()来调试alert()因为前者不强制数据类型。

Please replace your 请更换您的

 $("#btnPost").click(function () {
                        alert(originvalue);
                    }); 

with

$("#btnPost").click(function () {
                        alert($("#txtName").val());
                    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM