在我的ASP.Net MVC的核心应用
视图
<form>
<div class="container">
<div class="row">
<div class="col-md-offset-2 col-md-4">
<div class="form-group">
<input type="text" class="form-control small" asp-for="UserName" />
</div>
<div class="form-group">
<input type="text" class="form-control small" asp-for="Password" />
</div>
<div class="form-group">
<a class="btn btn-sm btn-success pull-right" asp-action="Validate" asp-controller="LogIn" onclick="ValidateLogin()">Log In</a>
<input type="submit" value="LogIn" asp-action="Validate" asp-controller="LogIn" onclick="ValidateLogin(this)" />
</div>
</div>
</div>
</div>
打字稿代码
function ValidateLogin(e:Event) {
var username = (document.getElementById('UserName') as HTMLInputElement).value;
var password = (document.getElementById('UserName') as HTMLInputElement).value;
if ((username.length > 0) && (password.length > 0)) {
}
else {
alert('Fields required');
e.preventDefault();
}
}
如果字段为空比它应该终止该请求,但它只显示警报和E,preventDefault()方法是无效的在这里。
我也试过返回false,但似乎没有在这里工作。它不应该去操作方法的preventDefault后或返回虚假陈述
谁能告诉我,我在这里缺少在这个非常简单的任务是什么?
更新1
如果我更改代码下面的方式,比它的工作原理
document.getElementById('btn').onclick = function (e) {
var username = (document.getElementById('UserName') as HTMLInputElement).value;
var password = (document.getElementById('UserName') as HTMLInputElement).value;
if ((username.length > 0) && (password.length > 0)) {
}
else {
alert('Fields required');
return false;
}
}
不过我不知道为什么,当我的方法把它包起来,而不是直接与.onclick调用的不工作()
我也试过返回false,但似乎没有在这里工作。它不应该去操作方法的preventDefault后或返回虚假陈述
作为qazxsw POI指出,您的qazxsw POI功能期待一个qazxsw POI作为参数。但你通过了kemicofa's answer。
让我们来检查你的代码:
ValidateLogin
在这里,Event
意味着你告诉浏览器通过这个this
DOM元素<input type="submit" value="LogIn" asp-action="Validate" asp-controller="LogIn" onclick="ValidateLogin(this)" />
function作为参数。作为ValidateLogin(this)
元素没有input
方法,它失败。
不过我不知道为什么,当我的方法把它包不能正常工作,而不是直接与
ValidateLogin()
调用
总之,这里的Input
引用的DOM元素这是我们重视的事件处理程序之一。无论如何,preventDefault
不是.onclick()
的实例。
如果你喜欢与this
HTML属性绑定的事件处理程序,您可以使用this
变量:
onclick="ValidateLogin(this)"onclick="ValidateLogin(event)"
因为Event
可能被视为为您on{eventtype}="script_code"
预先定义的局部变量。有关详细信息,请参阅event
这两个调用通过从JavaScript设置event
和调用script_code
用内嵌HTML属性应该正常工作。
Registering on-event handlers
你的问题是你ValidateLogin方法。你通过“本”方面,你的方法需要一个事件参数。
做到这一点,而不是。
.onclick=function(event){/**/};
从您的提交按钮ValidateLogin(event)
。