Saturday, March 10, 2012

ASP.Net MVC 3 : Passing query string between view pages

There will be scenarios where we need to redirect back to a page after some operations in different controllers. Examples for such scenario are the login with registration. If you are developing a shopping site using ASP.Net MVC you need to allow users to browse through the site without authenticating. But when the user selects checkout you may need to show the authenticate page and redirect to the page from where the login started. Sometimes the users may not have the credentials in your site. In that case they may goto the registration page and upon validating the confirmation code you need to redirect them to the product page where they started the authentication process. It would be really difficult to do accomplish this without passing the query string among the pages. Lets see how we can do this.

Redirect to an action with query string
If you are in an action register belongs to AccountController and want to redirect to the confirm page.Try the below

this.RedirectToAction("confirm""account"new { returnUrl = returnUrl });

This will redirect to a page with URL as

/account/confirm?returnUrl=<value of returnUrl>

Showing action links with query string
You have a Login page and you need to redirect to the page from which this page is called after successful login you obviously use the query string. But how to handle if you need to provide the register link in the same login page where you need to redirect to the calling page after successful registration? \
Answer is simple you need to have the query string of login page propagated to the register link as well.Isn't it?

RAZOR page of login

RouteValueDictionary rvd = new RouteValueDictionary(ViewContext.RouteData.Values);
foreach (string key in Request.QueryString.Keys)
    rvd[key] = Request.QueryString[key].ToString();
@: &nbsp;
@Html.ActionLink("[register]""register""account", rvd, null)

This will transfer the query string values in the url to the action link.

1 comment:

Blogger said...

Looking for the Best Dating Site? Create an account to find your perfect match.