What is best practice for passing model object? (revised)

Coreysan 1,811 Reputation points
2025-01-05T04:42:50.97+00:00

What is the best way to pass object to another controller/action? Right now I have this:

        return RedirectToAction("myaction", "mycontroller", new { x = rsum.ToString() });
```Should I modify this line, or use tempdata, or other?

Developer technologies | ASP.NET | ASP.NET Core
{count} votes

2 answers

Sort by: Most helpful
  1. Anonymous
    2025-01-06T02:48:26.1366667+00:00

    Hi @Coreysan,

    Should I modify this line, or use tempdata, or other?

    Firstly you need know that RedirectToAction will redirect to the action with route object. That is to say the object will display in the address bar.

    1. If the object is small and not sensitive, your current approach is fine.
      a. Pass simple type data should be like:
         return RedirectToAction("YourAction", "YourController", new{id=1});
      
      b. Pass complex type model should be like:
         var model = /*create a model*/;
         return RedirectToAction("YourAction", "YourController", model);
      
    2. If the object is larger or sensitive, consider TempData or Session.

    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

  2. Bruce (SqlWork.com) 78,086 Reputation points Volunteer Moderator
    2025-01-08T18:23:07.0466667+00:00

    the RedirectToAction converts the passed object (should only properties that convert to string) to query string name/value pairs. this will always work, but the user can edit the query string and refetch. if this is an issue, then encrypt the value and convert the binary to base64url string.

    TempData passes the object value via a cookie (or session). so the only issue is if cookies are disabled. the same is true for session, cookies must be enabled.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.