Friday, September 23, 2011

Passing value within 2 webpages using Razor syntax

Following will be the example if you would like to use Request QueryString to pass value between 2 CSHTML page.

We have have 2 web pages, Page.cshtml and Page2.cshtml. Under Page.cshtm, there will be a textbox and a button, whatever user enter in the textbox, it will be pass over to Page2.cshtml.

Here the code on Page.cshtml. We use the Request.Form to capture the input by the user from the textbox. The value then store in the variable "formValue" which will be pass over to Name under Response.Redirect.

@{
var formValue = Request.Form["myTextBox"];
if (IsPost)
{

Response.Redirect("Page2.cshtml?name=" + formValue);

}
}







Here's the code on Page2.cshtml, please take note on the previous code Response.Redirect("Page2.cshtml?name=" + formValue); we actually pass the value to the variable named "NAME". so in Page2.cshtml, we will capture the value under NAME. We used Request.QueryString to capture the value from the URL which will be http://localhost/page2.cshtml?name=WHATEVERUSERINPUT.




For this example, queryValue will return the value of "WHATEVERUSERINPUT".