1

I am just starting MVC and I would like to know the best practice to pass sensitive information like IDs across views ...

Let's assume that I have a scenario. I have a car service managing MVC application which allow users to choose product for their registered car.

The user have to register their car first before they choose a product for their service.

In register view, they fill out the car detail and it redirects to purchase product page when they click the submit button. At the time when they click the submit button, we store car details with user ID (which I can get from Identity) and generate unique car ID from the database. I want to pass this newly created car ID to next view.

In purchase product page, they can choose different product A or B and when they choose, it redirects to checkout page.

What I want to achieve now is then in checkout page, how securely we can carry the car ID that user get after they have registered their car and product ID from previous product view so I can process transaction with userID, carID, and productID.

Is Session way to go with this ? Or any other better way to tackle this problem .? Someone with small example will be great help for me.

Thanks,

superted
  • 315
  • 1
  • 8
  • 21
  • Might be worth you looking at the [MVC Music Store tutorial](http://www.asp.net/mvc/overview/older-versions/mvc-music-store/mvc-music-store-part-1) to see how they implement this, and you could consider using one of the free open-source e-commerce shopping carts such as [nopCommerce](https://nopcommerce.codeplex.com/) –  Nov 07 '14 at 02:22
  • Just store it in the database against the user's ID. You should avoid the session for this. – heymega Nov 07 '14 at 09:30
  • Any reason why I should avoid the session ? – superted Nov 09 '14 at 12:15

1 Answers1

1

In your example given I would certainly recommend storing the ID in a session. The web is a stateless beast, and what you're essentially after doing is recording state for the duration of the user's visit to the website/application - this is essentially what sessions are designed to do.

Creating, storing and retrieving data from a session is simple and can be done like so:

Setting a variable in the session object

[HttpPost]
public ActionResult Login(int carId)
{
    ...
    Session["carId"] = carId;
    ...
}

Retrieving a variable from the Session object

public ActionResult Load()
{
    ...
    int carId = Session["carId"];
    ...
}

Whilst this is a basic example, it gives you an idea as to how to store/retrieve simple types of data from a session.

For storing more information such as large objects you can use the [Serialize] class attribute outlined in my answer in this post.

Community
  • 1
  • 1
Joseph Woodward
  • 9,191
  • 5
  • 44
  • 63