c# - ASP MVC : Index action with optional string parameter

标签 c# .net asp.net-mvc asp.net-mvc-4 routes

我想要一个带有可选字符串参数的索引操作。我无法让它工作。

我需要以下路线:

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 。这是我发现的错误:

enter image description here

最佳答案

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/

相关文章:

c# - 如何在不进行系统调用的情况下获得恒定的字符串长度?

.net - Azure 部署中心在部署时生成错误

c# - 在 Perfmon 中看到高 "% Time in GC"的原因

asp.net - 用于 ASP.NET MVC 的基于 XAML 的 View 引擎

c# - 具有 Text 属性的多个按钮的一个 Click 事件

c# - 使用 powershell 脚本通过 c# 重新启动应用程序池

c# - 如何在 Blazor 中实现拖放?

c# - 识别我的 dotnet 版本

c# - 传入字典的模型项在 ASP.net MVC 中属于“System.Collections.Generic.List...”类型

asp.net-mvc - 如何在 MVC2 下以编程方式设置母版页