c# - 即使在函数中将 returnValue 设置为 False 后, Controller 操作也会执行

标签 c# javascript html asp.net-mvc

我有一个带有一个文本框和一个按钮的表单。在这里,我需要验证用户是否没有在文本框中输入无效数据,因此我在 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/

相关文章:

javascript - 从浏览器打印时 jQuery 是否运行?

html - 像 Bootstrap 3 中那样的 Bootstrap 4 导航栏菜单(移动)样式?

jquery - 文本幻灯片跳跃淡入淡出

javascript - 显示带有复选框的 jquery <div>

c# - StackExchange Redis 在使用异步插入/读取数据时丢失了一些键

c# - .NET 中的 Erlang 风格的轻量级进程

c# - 如何在 C# 中从 IMDB 获取信息

javascript - 使用 javascript 自动求和和减去

javascript - 滚动渐变时如何更改div颜色?

c# - 使用 Entity Framework Fluent 语法或内联语法编写递归 CTE