Asp.net mvc 4 如何在ASP.NET MVC 4中定义默认操作参数

Asp.net mvc 4 如何在ASP.NET MVC 4中定义默认操作参数,asp.net-mvc-4,Asp.net Mvc 4,我正在跟随Pluralsight视频学习MVC4 在学习操作参数的默认值时,我在RouteConfig.cs中定义了以下设置 routes.MapRoute( name: "cuisine", url: "cuisine/{name}", defaults: new { controller="cuisine", action="search", name=""}); 我已使用Search()作为操作方法创

我正在跟随Pluralsight视频学习MVC4

在学习操作参数的默认值时,我在RouteConfig.cs中定义了以下设置

        routes.MapRoute(
            name: "cuisine",
            url: "cuisine/{name}",
            defaults: new { controller="cuisine", action="search", name=""});
我已使用Search()作为操作方法创建了CuisineController,如下所示:

    public ActionResult Search(string name="India")
    {
        var message = Server.HtmlEncode(name);
        return Content(message);
    }
根据我看到的视频,如果URL中没有传递任何内容,那么印度应该作为输出。 但是,我得到的是空字符串。
我哪里做错了?

您必须使用UrlParameter。可选

routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{name}", // URL with parameters
                new { controller = "Home", action = "Search", name = UrlParameter.Optional } // Parameter defaults
            );

public ActionResult Search(string name = "India")
        {
            var message = Server.HtmlEncode(name);
            return Content(message);
        }

这在页面中完美地显示了“印度”。

感谢您的快速回复。我已使用以下URL在我的CuisineController中调用搜索操作方法。这意味着我没有传递任何参数,对吗?即使这样,我也不能将印度作为输出。您必须使用urlparmeter.Optional。我已经编辑了我的答案,请查看。希望有帮助。谢谢你的短信。你是对的。我已经记下了你的答案。随着我的行动,你的两张反对票消失了。再次感谢。如果从路由默认值中删除name=”“,该怎么办?“name”是必需的,因为它是“url”参数-{name}的一部分