Can I get some data in controllers from view use viewdata?

Alick Wang 266 Reputation points
2023-12-12T02:11:50.4633333+00:00

Can I get some data in controllers from view use viewdata?

In view ,like

@{
    Layout = "_Layout";    
    ViewData["pid"] = "1";
}

In view , when submit a form , in controller ,like

public IActionResult do()
{
string pid=ViewData["pid"];//get "1"?
}
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,238 questions
0 comments No comments
{count} votes

Accepted answer
  1. Ping Ni-MSFT 2,405 Reputation points Microsoft Vendor
    2023-12-12T05:18:12.7933333+00:00

    Hi @Alick Wang

    ViewData only work for current request, I suggest you using TempData.TempData works during the current and subsequent request.

    View:

    @{
        Layout = "_Layout";
        TempData["pid"] = "1";
       
    }
    

    Controller:

    
    public async Task<IActionResult> Do()
    {
     
        string pid = TempData["pid"] as string;//get "1"
        //...
    }
    

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Rena

    0 comments No comments

0 additional answers

Sort by: Most helpful