Jass
Jass

Reputation: 381

How to pass single parameter in RedirectToAction to different controller in ASP .NET MVC?

I know, a similar question is asked before. But I couldn't find exact similar case. I want to pass model object in return RedirectToAction() to method in another controller. My code:

  MyModel mdl_obj=new MyModel();
  return RedirectToAction("mthdInAnotherController", "AnotherControllerName",new { mdl_obj = mdl_obj });

I am assigning some values to model object and sending it to method in another controller. But that method has more than one arguments and I am not passing those. While passing, model object is not null but in another controller , I am getting null value for model object. What could be the reason?

Upvotes: 4

Views: 2705

Answers (2)

Epic Chen
Epic Chen

Reputation: 1372

TempData is for this scenario. TempData is used to transfer data from view to controller, controller to view, or from one action method to another action method of the same or a different controller.

The usage is

    public ActionResult Foo()
    {
        // Store data into the TempData that will be available during a single redirect
        TempData["Model"] = new MyModel();
    
        // If you store something into TempData and redirect to a controller action that will be available to consume the data
        return RedirectToAction("bar");
    }
    
    public ActionResult Bar()
    {
        var mdl_obj = TempData["Model"];
        ...
    }

Reference: ViewBag, ViewData and TempData

Upvotes: 1

Andrew Halil
Andrew Halil

Reputation: 1323

You will first need to check that the model class is declared within your HTML view like this:

@model MyModel

Without it the view cannot bind data from the controller.

The model class declared in your view must match the class returned by the controller method:

[HttpGet]
public ActionResult mthdInAnotherController(string param1, string param1, ..., paramN)
{
    MyModel = new MyModel();
    // populate model here
    ...
    ...
    return View(myModel);
}

Also check the controller method called has matching input parameter names from your RedirectToAction() parameter object:

return RedirectToAction("mthdInAnotherController", "AnotherControllerName", 
    new { 
        param1 = val1, param2 = val2, ... ,paramN = valN 
    });

Upvotes: 2

Related Questions