![](/img/trans.png)
[英]An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. What to do?
[英]An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters`
我正在 .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");
}
來自 RouteConfig 的代碼片段:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
當我點擊 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
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 }
);
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);
}
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 }
);
嘗試在RouteConfig中添加它
routes.MapRoute(
"Student", // Route name
"Edit/{StudentId}", // URL with parameters
new { controller = "Student", action = "Edit" } // Parameter defaults
);
沒有配置路由
$.ajax({
type: "POST",
cache: false,
url: '/Student/Edit/?StudentId='1,
dataType: 'json',
...
...
..
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.