anthonypliu
anthonypliu

Reputation: 12437

How to pass a variable through url and use it inside a controller

I have this controller:

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());
        }
    }

I type in the url Profiles/Details/hello, but it does not work, if I do Profiles/Details?UserName=hello then it works. I have another ActionResult just like this except taking in an int id as parameter and it works fine with the first url format.

Upvotes: 0

Views: 454

Answers (1)

Mikael Östberg
Mikael Östberg

Reputation: 17166

You have to register a new route, something like this:

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

Upvotes: 3

Related Questions