Can we pass model as a parameter in RedirectToAction?

Amit picture Amit · Mar 19, 2014 · Viewed 100.3k times · Source

I want to know, there is any technique so we can pass Model as a parameter in RedirectToAction

For Example:

public class Student{
    public int Id{get;set;}
    public string Name{get;set;}
}

Controller

public class StudentController : Controller
{
    public ActionResult FillStudent()
    {
        return View();
    }
    [HttpPost]
    public ActionResult FillStudent(Student student1)
    {
        return RedirectToAction("GetStudent","Student",new{student=student1});
    }
    public ActionResult GetStudent(Student student)
    {
        return View();
    }
}

My Question - Can I pass student model in RedirectToAction?

Answer

Murali Murugesan picture Murali Murugesan · Mar 19, 2014

Using TempData

Represents a set of data that persists only from one request to the next

[HttpPost]
public ActionResult FillStudent(Student student1)
{
    TempData["student"]= new Student();
    return RedirectToAction("GetStudent","Student");
}

[HttpGet]
public ActionResult GetStudent(Student passedStd)
{
    Student std=(Student)TempData["student"];
    return View();
}

Alternative way Pass the data using Query string

return RedirectToAction("GetStudent","Student", new {Name="John", Class="clsz"});

This will generate a GET Request like Student/GetStudent?Name=John & Class=clsz

Ensure the method you want to redirect to is decorated with [HttpGet] as the above RedirectToAction will issue GET Request with http status code 302 Found (common way of performing url redirect)