我有一个带有一个文本框和一个按钮的表单。在这里,我需要验证用户是否没有在文本框中输入无效数据,因此我在 site.masters“head”中有一个函数,称为“onclick”事件。问题是,即使将“returnValue”变量设置为“False”, Controller 操作仍在执行,并且出现以下错误:
Server Error in '/' Application.
The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.int32' for method 'System.Web.Mvc.ActionResult AddStudent(System.DateTime)' in 'Student.Controllers.HomeController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters
Controller 操作:
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>
如何解决这个问题?
提前致谢
最佳答案
您需要返回
returnValue。现在您将其设置为 false,但没有对其执行任何操作。
关于c# - 即使在函数中将 returnValue 设置为 False 后, Controller 操作也会执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9622011/