Arianule
Arianule

Reputation: 9043

route not mapping mvc 3

I am new in mvc and I have a situation where I am convinced that I am mapping a route correctly although it is not.

it is a very basic login form with the option of passing in parameters.

this is the html

<li><a href="@Url.Action("LoginForm", "Home", new {userName="user"})">Login</a></li>

and this is the action method in the 'Home' controller

public ViewResult LoginForm(string userName)
    {

        return View();
    }

This is how is my attempt at mapping the route

routes.MapRoute(
            null,
            "Login/{userName}",
            new { controller = "Home ", action = "LoginForm", UrlParameter.Optional }
            );

The url is however displaying as follow

/Home/LoginForm?loginUser=user

my aim would be the following

Login/user

Advice perhaps as to why it is not mapping correctly. I have already registered a number of routes in the Global.asax.cs file. Could it have something to do with the order with which they were registered?

Upvotes: 1

Views: 97

Answers (3)

Andrei V
Andrei V

Reputation: 7506

You are hitting a different address than the one specified in MapRoute. The mapped route will not fire. Change both the parameter and the action name.

<li><a href="@Url.Action("Login", "Home", new {userName="user"})">Login</a></li>

You need to access /Home/Login not /Home/LoginForm. The routing is done automatically if the right address is accessed.

EDIT: Following your address edit:

  • As far as I know, you cannot generate a link such as Login/{userName} using Url.Action; if you don't specify a controller, this defaults to Home controller
  • You can however access the Login/{userName} link directly from the browser (due to the mapped route)
  • You can create a "static" (i.e. classic) link, passing a hard-coded address:
    <li><a href="/Login/user">Login</a></li>

Please note that the userName added/removed per JavaScript.

Upvotes: 0

Satpal
Satpal

Reputation: 133403

Use userName instead of loginUser

<li><a href='@Url.Action("LoginForm", "Home", new {userName="user"})'>Login</a></li>

Upvotes: 1

AFetter
AFetter

Reputation: 3584

Try this:

<li><a href="@Url.Action("LoginForm", "Home", new {userName="user"})">Login</a></li>

change the parameter loginUser to userName.

Upvotes: 3

Related Questions