Search code examples
c#asp.net-mvcrazordatabase-first

How to pass Session data from controller to View (MVC)


I'm new into MVC and I'm having a hard time solving this following issue. I got a userID via Session["LoggedUserID"] as it get once the user log in. I want to pass it to following cshtml code(or directly in controller?) which I do not understand for the moment. This action occur once user want to create a new post.

inside cshtml view(code created automatically from Controller):

     @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.CreatorUserId, "CreatorUserId", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("CreatorUserId", null, htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.CreatorUserId, "", new { @class = "text-danger" })
        </div>
    </div>

My controller code:

 [HttpGet]
        public ActionResult Create()
        {
            return View();
        }

[HttpPost]
public ActionResult Create(Review review)
{  
    if (ModelState.IsValid) {

        db.Reviews.Add(review);
        db.SaveChanges();

        return RedirectToAction("Index");
    }
    return View(review);        
}

How do I pass Session["LoggedUserID"] to cshtml (or directly via controller)? Review table is using userID as FK for user ID.

EDIT: The error message I get for my current code is:

There is no ViewData item of type 'IEnumerable' that has the key 'CreatorUserId'.

Any help is much appreciated. Thanks.


Solution

  • If it is for saving with entity, there is no need to pass it to the view and send it back to server. You can use it directly in your HttpPost action method.

    [HttpPost]
    public ActionResult Create(Review review)
    {  
        if (ModelState.IsValid) 
        {
            if(Session["LoggedUserID"]==null)
            {
               return Content("Session LoggedUserID is empty");
            }
    
            review.UserID = Convert.ToInt32(Session["LoggedUserID"]);   
            db.Reviews.Add(review);
            db.SaveChanges();
    
            return RedirectToAction("Index");
        }
        return View(review);        
    }
    

    I also added an If condition to check whether Session["LoggedInUserID"] is null before reading it to an int variable( UserID property). Ideally you may move this out of the action method to check whether user is logged in or not (May be an action filter like this)