Send and Receive data in .cshtml page

21,086

Solution 1

You can access the query string using Request.QueryString["key"]. So I suppose you'll want to use something like this:

@{
    var myProductId = Request.QueryString["id"];
}

Caveat: Of course this is would be a bad practice, and normally the MVC pattern calls for you to pull the ID in your Controller's action, fetch model data, and return that model data to the View. The View should know as little about things like the Query String, and any program logic, as possible.

public class ProductController : Controller
{
    public ActionResult ProductDetails(string id)
    {
        MyProduct model = SomeDataSource.LoadByID(id);
        return View(model);
    }
}

Solution 2

You can access it via Request object:

@Request.Params["id"]

Solution 3

Nobody mentioned that you'll probably want to change your link:

<a href="ProductDetails.cshtml?id=1"> Details </a>

to something like:

<a href="@Url.Action("ProductDetails", "Product", new {@id = 1})" >Details</a>
Share:
21,086
Billz
Author by

Billz

Updated on July 09, 2022

Comments

  • Billz
    Billz almost 2 years

    I am doing my homework in which I am developing a shopping site in asp.net MVC 3 and currently I am doing my work only in views. I have a product page and on the click of details I have to open product detail page.

    <a href="ProductDetails.cshtml"> Details </a>
    

    I have multiple products and I want to tell my product detail page that which product details is opened. One way is this I can append Id with URL like

    <a href="ProductDetails.cshtml?id=1"> Details </a>
    

    But I am unable to understand how I can receive this id on the product detail page since I have no controller and no model and I am fetching data using compact database on the .cshtm page using server side code.