Reputation: 4966
I have a form with one textbox and one button. Here I need to validate if users are not entering invalid data in the textbox so I have a function in site.masters "head" which is called "onclick" event. The issue is, even after setting the "returnValue" variable to "False" the controller action is being executed and I get the following error:
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 Action:
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"]);
}
Here is my javascript code from Site.Master:
<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>
Here is my form code from my view:
<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>
How do I resolve this?
Thanks in advance
Upvotes: 0
Views: 225
Reputation: 5667
Update your onclick event to:
onclick="return verifyInput();"
or
onclick="verifyInput"
Also, for form validation, you should be checking that on submit, instead of on click. That way you capture the miscellaneous times a form submits, such as when they hit the enter button.
It would be something similar to:
<form ... onsubmit="return verifyInput();">
Upvotes: 2
Reputation: 13115
This problem has something more to do with your Routes. Does your default route, or the one for this action, look something like this?
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
If not, you will need to append the studentId
to the end of your from action before submitting it.
maybe something like:
if (document.getElementById('studentId').length != 10) {
...false...
} else {
document.getElementById('Form1').action = document.getElementById('Form1').action = document.getElementById('studentId').value;
}
Also, it may help to set maxlength as "10" instead of 10, wrapping it with quotes.
Upvotes: 1
Reputation: 6042
You need to return
returnValue. Right now you're setting it to false, but not doing anything with it.
Upvotes: 4