Anajrob
Anajrob

Reputation: 577

How to detect which user clicked the link MVC3 membership

When user clicks the link this method takes the user id and other data and writes it to the database. I can't seem to find a way to track what is the user id since the id is automatically generated.

I am using membership base separately from my base. In order to find userID I was trying to compare UserName strings. I get this error: "An unhandled exception was generated during the execution of the current web request." Also "Cannot create an abstract class." Is there a better way to compare two strings form the two databases? Or is there a better way? This is my first time using lambda expressions.

I tried using Single() and First() instead of Where(), but I still get the same error.

[HttpPost]
public ActionResult AddToList(Review review, int id, HttpContextBase context)
    {
        try
        {
            if (ModelState.IsValid)
            {
                //User user = new User();
                //user.UserID = db.Users.Where(c => c.UserName == context.User.Identity.Name);
                User user = new User();
                Movie movie = db.Movies.Find(id);
                review.MovieID = movie.MovieID;

                string username = context.User.Identity.Name;
                user = (User)db.Users.Where(p => p.UserName.Equals(username));

                review.UserID = user.UserID;
                db.Reviews.Add(review);
                db.SaveChanges();
                return RedirectToAction("Index");
             };

        }
        catch (DataException)
        { 
            //Log the error (add a variable name after DataException)
            ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
        }
        return View(review);
    }

Upvotes: 1

Views: 136

Answers (1)

nathan gonzalez
nathan gonzalez

Reputation: 11987

you're problem is likely this line:

user = (User)db.Users.Where(p => p.UserName.Equals(username));

the Where() extension method returns an IEnumerable, not a single instance, so your implicit cast will fail every time. what you're looking for is either First() or FirstOrDefault(). First() will throw an exception if there is no match though, while FirstOrDefault()will return a null if no match is found. the line should be :

user = db.Users.First(p => p.UserName.Equals(username));

you probably have bigger problems than that, but this is the cause of your current error.

EDIT

upon further looking at your code, you're asking for a HttpContextBase in your action result call. you never use it, and it's probably the cause of the Cannot create an abstract class exception. remove that parameter and see if you get any different results.

Upvotes: 1

Related Questions