[英]controller action being executed even after setting returnValue to False in function
我有一个带有一个文本框和一个按钮的表单。 在这里,我需要验证用户是否未在文本框中输入无效数据,因此我在site.masters“ head”中具有一个称为“ onclick”事件的函数。 问题是,即使将“ returnValue”变量设置为“ False”,也会执行控制器操作,并且出现以下错误:
“ /”应用程序中的服务器错误。
参数字典包含“ Student.Controllers.HomeController”中方法“ System.Web.Mvc.ActionResult AddStudent(System.DateTime)”的非空类型“ System.int32”的参数“ id”的空条目。 可选参数必须是引用类型,可为空的类型,或者必须声明为可选参数。 参数名称:参数
控制器动作:
public ActionResult AddStudent(int id)
{
StudentDataContext student = new StudentDataContext ();
var std = student.Students.FirstOrDefault(s => s.StudentId == id);
std = new Models.Student() { StudentId = id};
student.Students.InsertOnSubmit(std);
student.SubmitChanges();
TempData["Message"] = "Student " + id + " is added";
return RedirectToAction("Index", TempData["Message"]);
}
这是我来自Site.Master的javascript代码:
<script language="javascript">
function verifyInput() {
var returnValue = true;
if (document.getElementById('studentId').length != 10) {
returnValue = false;
alert("please enter a valid id")
Form1.studentId.value = "";
}
return returnValue;
}
</script>
这是我的表单代码:
<form id="Form1" method="get" action="/Home/AddStudent/" runat="server">
<label for="id">
<br /><br /> Student ID:
</label>
<input type="text" name="studentId" id="studentId" maxlength=10/>
<input type="submit" value="Add Student" onclick="verifyInput()"/>
</form>
我该如何解决?
提前致谢
您需要return
returnValue。 现在,您将其设置为false,但不对其进行任何操作。
将您的onclick事件更新为:
onclick="return verifyInput();"
要么
onclick="verifyInput"
另外,要进行表单验证,您应该在提交时(而不是单击)进行检查。 这样,您可以捕获表单提交的其他时间,例如当它们按下Enter按钮时。
它将类似于:
<form ... onsubmit="return verifyInput();">
此问题与您的路线有关。 您的默认路由或执行此操作的路由看起来像这样吗?
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
如果不是,您将需要在提交studentId
之前将其添加到from动作的末尾。
也许像这样:
if (document.getElementById('studentId').length != 10) {
...false...
} else {
document.getElementById('Form1').action = document.getElementById('Form1').action = document.getElementById('studentId').value;
}
同样,将maxlength设置为“ 10”而不是10可能会有所帮助,并用引号将其引起来。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.