如何通过url传递变量并在控制器中使用它

时间:2011-03-17 00:07:13

标签: c# asp.net asp.net-mvc-3

我有这个控制器:

public ActionResult Details(String UserName)
    {
        using (var db = new MatchGamingEntities())
        {
            var Users = from m in db.Users
                        join m2 in db.MyProfiles on m.UserId equals m2.UserId
                        where m.UserName == UserName
                        select new UserViewModel
                        {
                            UserName = m.UserName,
                            LastActivityDate = m.LastActivityDate,
                            Address = m2.Address,
                            City = m2.City,
                            State = m2.State,
                            Zip = m2.Zip
                        };

            return View(Users.SingleOrDefault());
        }
    }

我输入了url Profiles / Details / hello,但它不起作用,如果我做Profiles / Details?UserName = hello那么它可以工作。我有另一个ActionResult就像这样,除了接受一个int id作为参数,它与第一个url格式一起正常工作。

1 个答案:

答案 0 :(得分:3)

您必须注册一条新路线,如下所示:

routes.MapRoute(
   "RouteName",
   "profiles/{action}/{userName}",
   new { controller = "Profiles", action = "Details", userName = UrlParameter.Optional }
);