C# (编辑/5)不工作,但(编辑?id=5)在MVC 5中工作
我刚开始学习MVC,我试图将studentId作为参数传递给编辑页面。默认情况下,单击“编辑”链接时,会转到:C# (编辑/5)不工作,但(编辑?id=5)在MVC 5中工作,c#,asp.net-mvc,C#,Asp.net Mvc,我刚开始学习MVC,我试图将studentId作为参数传递给编辑页面。默认情况下,单击“编辑”链接时,会转到: localhost:63348/student/Edit/5 但它不起作用。它给了我这个错误 参数字典包含“WebApplication1.Controllers.StudentController”中方法“System.Web.Mvc.ActionResult EditInt32”的不可为null类型“System.Int32”的参数“StudentId”的null条目` 但如
localhost:63348/student/Edit/5
但它不起作用。它给了我这个错误
参数字典包含“WebApplication1.Controllers.StudentController”中方法“System.Web.Mvc.ActionResult EditInt32”的不可为null类型“System.Int32”的参数“StudentId”的null条目`
但如果我手动将其更改为:
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);
}
您需要添加属性[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);
}
两件事。首先,你的路线是错误的。[RouteEdit/{studentId:int]您缺少结束}。其次,route参数与method参数的名称不同。大小写很重要。@Amy,DefaultModelBinder不区分大小写您需要添加routes.MapMVCattributerRoutes;在RouteConfig.cs中的routes.MapRoute之前。。。要启用属性路由,并将[RoutePrefixStudent]添加到控制器定义中,FromUri给了我一个错误。我更改了路由,确保它在case[RouteEdit/{StudentId:int}方面匹配,但仍然不匹配working@ElDj您启用了属性路由吗?像这样使用[RouteEdit/{StudentId}]启用了属性路由并删除了int部分。现在,我得到了一个未找到的资源错误,你朝着正确的方向迈出了一步。同时添加[HttpGet]或适合您的情况的动词。
[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);
}