Nick Fleetwood
Nick Fleetwood

Reputation: 531

Altering database based on user id

I really looked, googled, this site, for a few days now, tried a bunch of different things, and I can't find an answer.

so, I'm trying to create a web application that will display client information after purchase. I'm using VS2012 express and C#, and I decided to use MVC4, mostly because there was a tutorial on ASP.NET that came pretty close to what I was looking to do. Any comments on my choices is not requested but also not unwelcome.

So the admin will enter all sales information at the end of each day. We record client phone numbers as account numbers in our sales protocol, so my thought was, to keep it simple, to just use the clients phone number as a login to the web application as well. Also, that way, when a client logs into the site to view the database, the database would filter automatically so that the particular client could only see their transactions.

The tutorial I followed is here.

I figured out that this is the point where the filter needs to be applied, but i'm having a lot of trouble doing so. The controller is named "MainController" The database is named "Main", table is "Mains" "AccountNumber" is the field in the db that should match the Current User Id

public ActionResult Index()
{
    return View(db.Mains.ToList());
}

As I understand it, I have to place [InitializeSimpleMembership] above, then grab the UserId, then define it as the filter.

Upvotes: 3

Views: 99

Answers (1)

Amin Saqi
Amin Saqi

Reputation: 18977

First of all, you should decide one of these way:

1) keeping login and user info in a separate table and let the SimpleMembership(SM) does its default jobs.

2) Using an existing table so store users info and tell the SM which table is for.

Approach One:

To handle this approach, all you need is that you create users manually(as you do, I think) and add an extra line to the action method which is responsible of creating customers:

[HttpPost]        
public ActionResult Create(Customer model)
{
    if (ModelState.IsValid)
    {            
        db.Customers.Add(model);
        try
        {
            db.SaveChanges();

            // here it is ...
            WebSecurity.CreateUserAndAccount(model.Phone, model.Password);
        }
        catch 
        {
            insertError = true;
        }
        // .. Other codes ...
} 

Now, your customers can simply login to the site with their phone no. as username and that password.

And to retrieve items related to a specific user - which is currently logged into site - simply use the following query:

public ActionResult Index()
{
    return View(db.Mains.Where(m => m.AccountNumber == User.Identity.Name)
        .ToList());
}

If you also need approach two, tell me to update my answer and put it here

Upvotes: 1

Related Questions