我刚刚开始学习MVC,我试图将studentId
作为参数传递给编辑页面。默认情况下,当您单击“编辑”链接时,它将转到:
localhost:63348/student/Edit/5
但它不起作用。它给了我这个错误
参数字典包含参数' StudentId'的空条目。非可空类型的System.Int32' for method' System.Web.Mvc.ActionResult Edit(Int32)'在' WebApplication1.Controllers.StudentController' .`
但如果我手动将其更改为:
localhost:63348/student/Edit?studentid=5
然后它起作用。它们应该是同一个东西,并且几乎以同样的方式工作吗?
这是我的控制人员:
public IList<Student>studentList = new List<Student>{
new Student() { StudentId = 1, StudentName = "John", Age = 18 } ,
new Student() { StudentId = 2, StudentName = "Steve", Age = 21 } ,
new Student() { StudentId = 3, StudentName = "Bill", Age = 25 } ,
new Student() { StudentId = 4, StudentName = "Ram" , Age = 20 } ,
new Student() { StudentId = 5, StudentName = "Ron" , Age = 31 } ,
new Student() { StudentId = 6, StudentName = "Chris" , Age = 17 } ,
new Student() { StudentId = 7, StudentName = "Rob" , Age = 19 }
};
[Route("Edit/{studentId:int")]
public ActionResult Edit(int StudentId)
{
//Get the student from studentList sample collection
var std = studentList.Where(s => s.StudentId == StudentId).FirstOrDefault();
return View(std);
}
尝试添加特定的路由配置但是没有工作:
routes.MapRoute(
name: "StudentEdit",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Student", action = "Edit", id = UrlParameter.Optional }
);
答案 0 :(得分:1)
您需要添加属性[FromUri]
并更正编译问题(提供右括号}
且参数名称不相同。
[Route("Edit/{studentId:int}")]
public ActionResult Edit([FromUri] int studentId)
{
//Get the student from studentList sample collection
var std = studentList.Where(s => s.StudentId == StudentId).FirstOrDefault();
return View(std);
}