这是一个带有文本框和警告框的简单网页,用于在 Razor View 页面上显示其值:
<!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
。现在我想在警告框中显示此值。这是某种错误吗?我不知道这里缺少什么。
最佳答案
问题是因为您只在页面加载时设置了 originvalue
而 input
没有任何值。如果您想检索用户键入的值,请在点击处理程序内部设置该变量:
$(document).ready(function () {
$("#btnPost").click(function () {
var originvalue = $("#txtName").val();
console.log(originvalue);
});
});
另请注意,您的原始 JS 代码有一组右括号/方括号太多,您还应该使用 console.log()
来调试 alert()
因为前者不强制数据类型。
关于c# - 为什么我无法在 Razor 页面上获得正确的文本框值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37190441/