我是MVC和AJAX的新手,所以这可能是我犯的一个简单错误,但是使用下面的代码,我尝试以下错误getElementById("txtCount").value
:
<div class="row">
<div class="col-sm-4">
<div class="panel panel-primary">
<div class="panel-heading">
<h5 style="font-weight:bold;">Parameters</h5>
</div>
<div class="panel-body" id="parameters">
<form class="form-horizontal" id="frmParameters">
<div class="form-group">
<label for="txtCount" class="col-sm-4 col-form-label">Repeat</label>
<input type="number" min="1" max="100" step="1" id="txtCount" value="@Model.Count" class="input-sm col-sm-7" />
</div>
@if (Model.Grammar.SupportsMaxLength)
{
<div class="form-group">
<label for="txtMaxLength" class="col-sm-4 col-form-label">Max Length</label>
<input type="number" min="1" max="100" step="1" id="txtMaxLength" value="@Model.MaxLength" class="input-sm col-sm-7" />
</div>
}
<button name="btnGenerate" class="btn btn-primary pull-right" onclick="Generate();">Generate</button>
</form>
</div>
</div>
</div>
</div>
<script>
function Generate() {
var data = { count: document.getElementById("txtCount").value, maxLength: document.getElementById("txtMaxLength").value };
}
</script>
如果我更改:
var data = { count: document.getElementById("txtCount").value, maxLength: document.getElementById("txtMaxLength").value };
至:
var data = { count: document.getElementById("txtCount").value};
我不再收到错误了。
您的代码看起来不错。我认为您的代码尝试执行此行时出现错误
document.getElementById("txtMaxLength").value
因为在您的视图中,当某些if
条件返回时,您正在渲染此元素true
。因此,您的视图可能根本没有此输入元素,而您正在尝试阅读该内容!(检查页面的查看源,并搜索带有txtMaxLength
ID的输入。
最好的解决方案是在尝试读取值之前检查它是否存在。
var data = {
id: "@Model.Id",
count: document.getElementById("txtCount").value,
maxLength: null // or whatever default value you want
};
if (document.getElementById("txtMaxLength")) {
data2.maxLength = document.getElementById("txtMaxLength").value;
}
或者,如果您使用的是jQuery库,这很容易
var data = {
id: "@Model.Id",
count: $("#txtCount").val(),
maxLength:$("#txtMaxLength").val()
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句