我对MVC很新,但不是网络编程,我遇到的问题是将数据值从View传递到控制器,其中数据值与模型没有关联。
场景:我有两种类型的用户:学生和教师;基本上我正在尝试确定用户在网站上注册时要返回的视图。
EX:
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>
}
在调试中,我收到此错误:
参数字典包含参数&#39; stud&#39;的空条目。非可空类型&#39; System.Boolean&#39; for method&#39; System.Web.Mvc.ActionResult Preregister(Boolean)&#39;在&#39; Room_Booking_System.Controllers.AccountController&#39;。可选参数必须是引用类型,可空类型,或者声明为可选参数。 参数名称:参数
我不明白如何在不回发的情况下将此视图中的数据导入控制器。我想要一个基于响应的简单重定向。请帮助。
谢谢大家!
答案 0 :(得分:0)
如果要将checkbox的值直接绑定到action方法的参数,则action方法的参数名称应与checkbox的名称相同。所以,你的方法签名应该是这样的......
public ActionResult Preregister(bool faculty, bool student)
答案 1 :(得分:0)
您可以将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();
}
}
仍然总是建议练习使用某种模型并将其与视图强烈绑定,并将其用于在视图和控制器之间移动数据