如何在ASP.NET MVC中基于用户输入返回特定视图

本文关键字:用户 输入 返回 视图 于用户 ASP NET MVC | 更新日期: 2023-09-27 18:28:50

我是MVC的新手,但不是web编程,而且我在将数据值从视图传递到控制器时遇到了问题,因为控制器中的数据值与模型无关。

场景:我有两种类型的用户:学生和教师;基本上,我试图确定当用户在网站上注册时返回哪个视图。

例如:

    public ActionResult Preregister(bool fac, bool stud)
    {
        if (stud == true)
        {
            return StudentRegister();
        }
        else if(fac == true)
        {
            return FacultyRegister();
        }
        else
        {
            return Index();
        }
    }

因此,我希望从以下表单调用此ActionMethod:

@{
ViewBag.Title = "Preregister";
}
<h2>Registration</h2>
<p>Please indicate whether you are a student or faculty.</p>
@{
    bool chkValFac = false;
    bool chkValStud = false;
}
@using (Html.BeginForm("Preregister, Account"))
{
    <div class="pre-reg-container">
    <div class="checkbox-container">
        <div class="item">
            <label for="Student" style="width:70px;">Student</label>
            @Html.CheckBox("Student", chkValStud)
        </div>
        <div class="item">
            <label for="Faculty" style="width:70px;">Faculty</label>
            @Html.CheckBox("Faculty", chkValFac)
        </div>
    </div>
    <input name="continue" type="submit" id="continue" value="Continue" />
</div>
}

在调试中,我得到了这个错误:

参数字典包含"Room_Booking_System.Controllers.AccountController"中方法"System.Web.Mvc.ActionResult Preregister(Boolean)"的不可为null类型"System.Boolean"的参数"stud"的null条目。可选参数必须是引用类型、可为null的类型,或声明为可选参数。参数名称:参数

我不明白如何在不发回的情况下将数据从该视图获取到控制器中。我想要一个基于响应的简单重定向。请帮忙。

谢谢大家!

如何在ASP.NET MVC中基于用户输入返回特定视图

如果您想将checkbox的值直接绑定到操作方法的参数,那么操作方法的名称应该与checkbox的名称相同。所以,你的方法签名应该是这样的。。。

public ActionResult Preregister(bool faculty, bool student)

您可以将FormCollection作为输入。基本上,它将具有所有的形式元素。

public ActionResult Preregister(FormCollection fc)
{
    bool fac = fc["Faculty"];
    bool stud = fc["Student"];
    if (stud == true)
    {
        return StudentRegister();
    }
    else if(fac == true)
    {
        return FacultyRegister();
    }
    else
    {
        return Index();
    }
}

仍然建议使用某种模型,并将其与视图强绑定,并用于在视图和控制器之间移动数据