我正在尝试将字符串从 "text"
字段传递到 MVC 操作。表单变量称为查询
。 JavaScript 代码是:
<input type="text" class="form-control input-lg" placeholder="search..."
name="SearchBar" onkeypress="searchfunction()" />
<script>
function searchfunction()
{
if (event.keyCode == 13) {
var url = '"' + document.getElementById("#SearchBar").value + '"';
window.location = "@Url.Action("~/Home/Search")?query=" + url;
}
}
</script>
由此生成的 URL 应该是 domain/Home/Search?query=[contents of textfield]
但由于某种原因,它生成的 URL 类似于 domain/search.html?SearchBar= [SearchBar 的内容]
,我收到 0x800a138f - JavaScript 运行时错误:无法获取未定义或 null 引用的属性“值”
。我确信这两者是相关的,但是 .value
是我能找到的每个示例都建议使用的内容。
注意:我尝试使用 getElementById
与 #
和不带 #
的情况,对于输入的 name
属性也是如此。
我应该在 onkeypress
事件中传递字符串吗?我错过了一些简单的事情吗?这是 MVC 3 中的错误吗?
最佳答案
添加“id”属性:
<input type="text" class="form-control input-lg" placeholder="search..."
name="SearchBar" id="SearchBar" onkeypress="searchfunction()" />
并从 getElementById()
方法参数中删除“#”字符
关于用于 URL 生成的 Javascript 变量值未按预期评估,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22463234/