Dan*_*lba 7 .net c# asp.net-mvc routes asp.net-mvc-4
我想有一个带有可选字符串参数的Index操作.我无法让它发挥作用.
我需要以下路线:
http://mysite/download
http://mysite/download/4.1.54.28
Run Code Online (Sandbox Code Playgroud)
第一个路由将向索引视图发送空模型,第二个路由将发送带有版本号的字符串.
如何定义路径和控制器?
这是我的路线定义:
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 }
);
Run Code Online (Sandbox Code Playgroud)
这是控制器:
public ActionResult Index(string version)
{
return View(version);
}
Run Code Online (Sandbox Code Playgroud)
为什么这不起作用?我不是ASP MVC的专家,但这似乎是一个非常简单的问题.
http://mysite/downloads它工作正常http://mysite/downloads/4.5.6,控制器被正确调用,参数被正确传递.但后来似乎找不到视图.这是我发现的错误:
小智 7
string?将不起作用,因为string它不是值类型。
您可以为参数设置默认值:
public ActionResult Index(string version="")
{
return View(version);
}
Run Code Online (Sandbox Code Playgroud)
修复此问题的方法是以下列方式将参数传递给视图:
public ActionResult Index(string version)
{
return View((object)version);
}
Run Code Online (Sandbox Code Playgroud)
要么
public ActionResult Index(string version)
{
return View("Index", version);
}
Run Code Online (Sandbox Code Playgroud)
将string模型传递给视图时,如果模型是string参数,则由于以下重载方法,它将被解释为视图名称
View(String viewName)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15715 次 |
| 最近记录: |