我想要一个带有可选字符串参数的索引操作。我无法让它工作。
我需要以下路线:
http://mysite/download
http://mysite/download/4.1.54.28
第一个路由将向索引 View 发送一个空模型,第二个路由将发送一个带有版本号的字符串。
如何定义路由和 Controller ?
这是我的路线定义:
routes.MapRoute(
name: "Download",
url: "Download/{version}",
defaults: new { controller = "Download", action = "Index", version = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
这是 Controller :
public ActionResult Index(string version)
{
return View(version);
}
为什么这不起作用?我不是 ASP MVC 的专家,但这似乎是一个非常简单的问题。
错误
- 当我访问
http://mysite/downloads
时,一切正常 - 当我转到
http://mysite/downloads/4.5.6
时, Controller 被正确调用,参数也被正确传递。但似乎找不到该 View 。这是我发现的错误:
最佳答案
string?
将不起作用,因为 string
不是值类型。
您可以为您的参数设置一个默认值:
public ActionResult Index(string version="")
{
return View(version);
}
关于c# - ASP MVC : Index action with optional string parameter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25867200/