我正在.net MVC中创建一个演示应用程序.
下面是我的StudentController的代码片段.
public ActionResult Edit(int studentId)
{
var std = studentList.Where(s => s.StudentId == studentId).FirstOrDefault();
return View(std);
}
[HttpPost]
public ActionResult Edit(Student std)
{
//write code to update student
return RedirectToAction("Index");
}
Run Code Online (Sandbox Code Playgroud)
来自RouteConfig的代码片段:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Run Code Online (Sandbox Code Playgroud)
当我点击url时,http://localhost:54977/student/Edit/1我会遇到异常.
The parameters dictionary contains a null entry for parameter 'studentId' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Edit(Int32)' in 'MVC1.Controllers.StudentController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Parameter name: parameters.
但是当我点击url时它工作正常http://localhost:54976/student/Edit?StudentId=1.
我是.net MVC的新手.任何人都可以就此提出建议.
问题是由于您的路由配置.
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Run Code Online (Sandbox Code Playgroud)
http:// localhost:54977/student/Edit/1中的第三个参数映射到{id}而不是studentId.
您有两种方法可以解决此问题:
1)更改参数名称
public ActionResult Edit(int id) {
var std = studentList.Where(s => s.StudentId == id).FirstOrDefault();
return View(std);
}
Run Code Online (Sandbox Code Playgroud)
2)为Edit添加新路由:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"EditStudent",
"Edit/{StudentId}",
new { controller = "Student", action = "Edit" });
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13266 次 |
| 最近记录: |