0

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?

Kiwanax
  • 1,265
  • 1
  • 22
  • 41
  • What do the rest of your routes look like? Most likely something else is conflicting. Do you have this route entry *first* or *last*? It should be listed before more general routes. – Yuck Apr 12 '14 at 22:25
  • If the route is `"Users/Profile/{username}"`, the action method's parameter should be `username` as well... – Anthony Chu Apr 12 '14 at 22:25
  • @Yuck, this is the first route I created for the application, it's in the beggining, so, for now, is the only custom route. – Kiwanax Apr 12 '14 at 22:34
  • @AnthonyChu, the code I posted is using the id parameter since it's working to me. The second question is more important than the first. – Kiwanax Apr 12 '14 at 22:35

2 Answers2

1

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();
}
Mkh
  • 68
  • 1
  • 11
0

I might be reading this incorrectly, but if you change the name of the required parameter from id to username, it shouldn't return null

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