为什么我无法在Razor页面上获得正确的文本框值?

时间:2016-05-12 14:49:21

标签: c# jquery asp.net-mvc razor

这是一个简单的网页,带有文本框和警告框,可在剃刀视图页面上显示其值:

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

我已取出文本框值并将其分配给var originvalue。现在我想在警告框中显示此值。这是某种错误吗?我无法弄清楚这里缺少什么。

2 个答案:

答案 0 :(得分:3)

问题是因为您只在页面加载时设置input$(document).ready(function () { $("#btnPost").click(function () { var originvalue = $("#txtName").val(); console.log(originvalue); }); }); 没有值。如果要检索用户键入的值,请在里面设置该变量单击处理程序:

console.log()

另请注意,您的原始JS代码有一组结束括号/括号太多,您还应该使用alert()来调试var xmlRoot = "<root></root>"; var firstChildNode = "<firstChild></firstChild>"; var parser = new DOMParser(); var xmlDom = parse.parseFromString(xmlRoot, "text/xml"); var xmlChildNode = parse.parseFromString(firstChildNode, "text/xml"); xmlDom.appendChild(xmlChildNode); ,因为前者不会强制数据类型。

答案 1 :(得分:1)

请替换

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

$("#btnPost").click(function () {
                        alert($("#txtName").val());
                    });
相关问题