即使在函数中将returnValue设置为False之后,控制器动作仍在执行
本文关键字:控制器 之后 执行 False 函数 设置 returnValue | 更新日期: 2023-09-27 18:27:15
我有一个带有一个文本框和一个按钮的表单。在这里,我需要验证用户是否没有在文本框中输入无效数据,所以我在site.masters"head"中有一个函数,称为"onclick"事件。问题是,即使在将"returnValue"变量设置为"False"后,控制器的操作仍在执行,我会得到以下错误:
"/"应用程序中的服务器错误
参数字典包含参数的空条目方法的不可为null的类型"System.int32"的"id"中的"System.Web.Mvc.ActionResult AddStudent(System.DateTime)"Student.Controllers.HomeController"。可选参数必须是引用类型、可为null的类型或声明为可选类型参数参数名称:参数
控制器动作:
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"]);
}
这是我的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"
此外,对于表单验证,您应该在提交时进行检查,而不是在单击时进行检查。通过这种方式,您可以捕获表单提交的杂项时间,例如当他们点击回车按钮时。
它将类似于:
<form ... onsubmit="return verifyInput();">
这个问题更多地与Routes有关。你的默认路线,或者这个动作的路线,看起来像这样吗?
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可能会有所帮助,并用引号将其括起来。