Send and Receive data in .cshtml page

2019-04-11 11:36发布

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.

4条回答
三岁会撩人
2楼-- · 2019-04-11 12:03

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);
    }
}
查看更多
Evening l夕情丶
3楼-- · 2019-04-11 12:16
<div class="box-button">@Html.ActionLink("Details", "Course", new { id = item.id }, new { @class = "btn btn-default" })</div>
查看更多
家丑人穷心不美
4楼-- · 2019-04-11 12:18

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>
查看更多
虎瘦雄心在
5楼-- · 2019-04-11 12:26

You can access it via Request object:

@Request.Params["id"]
查看更多
登录 后发表回答