Search code examples
c#asp.net-mvcasp.net-routing

Route is matching on parameter, not action name / View isn't returning properly


I want to create a url like that below:

www.mywebapp.com/Users/Profile/john

I have the UsersController controller and the Profile action, which returns a ViewResult to the Profile page.

I've created a route to manage it:

routes.MapRoute(
    name: "ProfileRoute",
    url: "Users/Profile/{username}",
    defaults: new { controller = "Users", action = "Profile", username = UrlParameter.Optional }
);

The first question is: If i change {username} by {id}, it works. When I put {username} like parameter, the action gets NULL in the parameter. Why this?

Here's my action called Profile:

[HttpGet]
public ActionResult Profile(string id) {
    if (UsersRepository.GetUserByUsername(id) == null) {
        return PartialView("~/Views/Partials/_UsernameNotFound.cshtml", id);
    }
    return View(id);
}

I've added a View page to show the user profile. However, when the method ends its execution, I got another error:

The view 'john' or its master was not found or no view engine supports the searched locations. 
The following locations were searched:
~/Views/Users/john.aspx
~/Views/Users/john.ascx
...

The second question is: The page I have to show is Profile, not a page with the username's name. Why is it happening?


Solution

  • You are getting this error because you are passing a string (id) to the View function, this overload searches for a view with the name passed in the string (in this case the username).

    if you are simply trying to pass the username directly to the view you can use something like a ViewBag, so your code should look like this:

    public ActionResult Profile(string id) {
    if (UsersRepository.GetUserByUsername(id) == null) {
        return PartialView("~/Views/Partials/_UsernameNotFound.cshtml", id);
    }
    ViewBag.Username=id;
    return View();
    }