Dean
Dean

Reputation: 1550

Issue With ViewBag and Routes (MVC 3 - RC2)

I am having an issue with MVC-3 generating outgoing routes for me.

This is the address of the page I am on for both scenarios: http://localhost:1283/Conflict/Create/1200/300

Here are the map routes:

routes.MapRoute(
    null, // Route name
    "{controller}/{action}/{custId}/{projId}", // URL with parameters
    null, // Parameter defaults
    new { custId = @"\d+", projId = @"\d+" }
);

routes.MapRoute(
    null, // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);

Scenario 1:

From the controller:

public ActionResult Create(int custId, int projId)
{
    return View();
}

From the view:

@Html.ActionLink("Back to List", "Index", "Conflict", new { custId = ViewBag.custId, projId = ViewBag.projId }, null)

The resulting link that gets created.

http://localhost:1283/Conflict?custId=1200&projId=300

If I change the controller code to read as follows:

public ActionResult Create(int custId, int projId)
{
        ViewBag.custId = custId;
        ViewBag.projId = projId;

        return View();
}

I didn't make any changes in the view, only added those two lines to the controller and the following link is created:

http://localhost:1283/Conflict/Index/1200/300

What am I missing here? This is consistent behavior, I was able to reproduce this in other areas of my application. The "solution" is obvious, but my question is why?

Upvotes: 4

Views: 836

Answers (1)

Milimetric
Milimetric

Reputation: 13549

What's happening is the "?custId=1200&projId=300" part of your link is coming over from the link you used to GET the page you're on. So the Html.ActionLink call is doing this:

  1. generate the /Conflict/Index path
  2. look for the custId and projId in the ViewBag and finds the query string instead
  3. just appends your query string

In the second scenario, you're actually providing values, so the link is generating normally. Hope that helps.

Upvotes: 2

Related Questions