Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass model data to one controller to another controller

Tags:

c#

asp.net-mvc

pass model data to one controller to another controller is possible?

I want to passe the model data to one controller ro another controller.

[HttpPost]
        public ActionResult Personal(StudentModel student)
        {                          
                return RedirectToAction("nextStep", new { model = student});          
        }

        public ActionResult nextStep(StudentModel model)
        {           
            return View(model);
        }

in nextStep controller model value is null. How to do it? I need to StudentModel data in nextStep conreoller.

like image 618
aruni Avatar asked Jan 05 '15 06:01

aruni


1 Answers

You are using RedirectToAction. It will issue GET request. There are two ways you can pass your model here.

1. TempData

You need to persist the model in TempData and make RedirectToAction. However the restriction is it will be available only for the immediate request. In your case, it is not a problem. You can do it with TempData

public ActionResult Personal(StudentModel student)
{                          
       TempData["student"] = student;
       return RedirectToAction("nextStep", "ControllerName");          
}

public ActionResult nextStep()
{      
       StudentModel model= (StudentModel) TempData["student"];
       return View(model);
}

2. Passing in a query string

As the request is GET, we can pass the data as Query string with the model property name. MVC model binder will resolve the query string and convert it as model.

 return RedirectToAction("nextStep", new { Name = model.Name, Age=model.Age });

Also take a note passing sensible data in a Query string is not advisable.

like image 132
Murali Murugesan Avatar answered Oct 31 '22 13:10

Murali Murugesan