对于MVC中的循环不适用于不同的MapRoute

时间:2015-11-19 09:21:06

标签: c# html asp.net-mvc asp.net-mvc-5

我是MVC的新手,但我对C#相当不错。所以我在Visual Studio中摆弄了MVC,在那里我遇到了这个问题而且我找不到这个错误的原因。

我尝试打印变量n次。当我使用给定的URL

时,它工作得很好
http://localhost:18665/HelloWorld/Welcome?namelala=Rob&numtimes=3

输出符合预期 -

This is Rob
This is Rob
This is Rob

但是,当我尝试使用此URL时

http://localhost:18665/HelloWorld/Welcome/3/Rob

输出

This is Rob

我的RouteConfig代码:

namespace WebApplication1
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }


            );

            routes.MapRoute(
                name: "Name_Route",
                url: "{controller}/{action}/{numtimes}/{namelala}"

                );
        }
    }
}

HomeController Code

public ActionResult Welcome(string namelala, int numtimes=1)
        {
            ViewBag.Message = "This is " + namelala;
            ViewBag.numtimes = numtimes;

            return View();
        }

Welcome.cshtml代码

<h2>Welcome here</h2>
<ul>
    @{
        for (int i = 0; i < ViewBag.numtimes; i++)
        {
            <li>@ViewBag.Message</li>
        }

    }
</ul>

我做错了什么?

1 个答案:

答案 0 :(得分:0)

将您的路线配置更改为:

routes.MapRoute(
    name: "Name_Route",
    url: "{controller}/{action}/{namelala}/{numtimes}"
);

匹配您的方法签名:

public ActionResult Welcome(string namelala, int numtimes=1)

而且,根据斯蒂芬的评论,移动关于默认路线的路线