简体   繁体   English

如何将会话数据从控制器传递到视图(MVC)

[英]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. 我是MVC的新手,现在很难解决以下问题。 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. 当用户登录后,我通过Session["LoggedUserID"]获得了一个userID。我想将其传递给以下我暂时不了解的cshtml代码( 或直接在控制器中? )。 This action occur once user want to create a new post. 一旦用户要创建新帖子,就会发生此操作。

inside cshtml view(code created automatically from Controller): 在cshtml视图内(从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 )? 如何将Session["LoggedUserID"]传递给cshtml( 或直接通过控制器 )? Review table is using userID as FK for user ID. 复查表使用userID作为FK作为用户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'. 没有类型为“ IEnumerable”的ViewData项目具有键“ CreatorUserId”。

Any help is much appreciated. 任何帮助深表感谢。 Thanks. 谢谢。

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操作方法中直接使用它。

[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). 我还添加了一个If条件,以在将Session["LoggedInUserID"]读取为int变量( UserID属性)之前检查其是否为null。 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 ) 理想情况下,你可以移动了这一点的操作方法来检查用户是否登录或没有(可能是一个动作过滤器这样的

You need to bind the value ie "User ID" to view model or put it in view bag and you can access that in the cshtml. 您需要绑定值即“用户ID”以查看模型或将其放在视图包中,然后可以在cshtml中访问它。

Eg 例如

SampleViewModel vm = new SampleViewModel(){UserId = yourvalue}; 

You need to create this SampleViewModel class with a property called UserId and then you can use like this. 您需要使用一个名为UserId的属性来创建此SampleViewModel类,然后可以像这样使用。 You need to bind the view model to your cshtml also like - @model SampleViewModel.cs 您还需要将视图模型绑定到您的cshtml,就像- @model SampleViewModel.cs

or you can store the value in view bag. 或者您可以将值存储在查看包中。 ie

ViewBag.UserId = your-value; //You can call @ViewBag.UserId in cshtml page. 

Does this help? 这有帮助吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM