Samuel Davidson
Samuel Davidson

Reputation: 791

Remove serialized Model from URL of MVC controller action

Within my Home controller is the Index() action. Within Index() I return the a user object from the database using the currently authenticated user's ID:

return View(db.Users.Find(User.UserId));

That works properly and the URL is simply:

https://localhost:44301/

However elsewhere in the Home controller in a separate action I modify the current user and pass it back into the index view using:

return RedirectToAction("Index", user);

When I do this the URL becomes cluttered with a serialized version of the User model:

https://localhost:44301/Home/Index/4?Name=katrina&Administrator=True&PasswordEncodedHash=1000%3AqzWR8U6poGKshxHDsP%2B5yFhz5AZ01%2Fv1%3ASqCG0SliIpjX0M0jjkQqAf5aunTVS2gx&Tests=System.Collections.Generic.List%601%5BLearningManagementSystem.Models.Test%5D&UserTestAttempts=System.Collections.Generic.List%601%5BLearningManagementSystem.Models.UserTestAttempt%5D&Phones=System.Collections.Generic.List%601%5BLearningManagementSystem.Models.Phone%5D

I imagine I doing something dumb with the way I am redirecting the action however I cannot figure out how to fix this. I have tried adding a custom route but the "?Name=...." still gets appended to that.

(Edit) Code from that other action:

public ActionResult ToggleAdministrator()
{
    if (Request.IsAuthenticated)
    {
        var user = db.Users.Find(User.UserId);
        user.Administrator = !user.Administrator;
        db.SaveChanges();

        Response.Cookies.Add(cookie);

        return RedirectToAction("Index", user);
    }

    return RedirectToAction("Index", (User)null);
}

Upvotes: 2

Views: 373

Answers (1)

Ankush Jain
Ankush Jain

Reputation: 7079

I think you don't need to pass whole data while redirecting to some action using RedirectToAction.

Suppose you have an action Index in Home controller.

Public ActionResult Index(int id)
{
  -- write the code here to fetch data based on that id
  -- like
     var user = db.Users.FirstOrDefault(x=>x.Id = id);
     return View(user);
}

Now for this you just need to use redirect to action like below:

return RedirectToAction("Index", new { Id= 5 });

Note:

  • Never pass a complex type object in QueryString or in GET requests

Upvotes: 3

Related Questions