Ba5t14n
Ba5t14n

Reputation: 739

RedirectToAction to another Controller and passing parameters

I'm new in C# and espacially in ASP.NET MVC.

I have my HomeController, which contains this method:

public ActionResult Error(Error error)
{
    return View(error);
}

Now I have another Controller, which have the following line inside:

return RedirectToAction("Error","Home", new { Error = (new Error("ErrorName","ErrorDescription"))} );

As you might notice, I am trying to pass an Error object to the other controller, which then should pass it to the View.

The Error class I have written on my own, nothing spectacular:

public class Error
{
    public String name {  get; private set; }
    public String description {  get; private set; }
    public int number {  get; private set; }

    public Error(String name, String description)
    {
        this.name = name;
        this.description = description;
        number = 0;
    }
}

My problem ist that every time I try to access the error Variable in the HomeController, it is null. I have already googled an found some posts, but I don't understand, why my code isn't working. There are no errors, just this null value object.. I Appreciate any help! :)

Upvotes: 8

Views: 17567

Answers (3)

Abbas Galiyakotwala
Abbas Galiyakotwala

Reputation: 3019

You cannot pass complex objects in an url like that. You will have to send its constituent parts:

public ActionResult YourAction()
{

   // Here user object with updated data

   return RedirectToAction("Error","Home", new { 
        name = "ErrorName", 
        description = "ErrorDescription", 
        number = 0
   });
}

Upvotes: 1

user3559349
user3559349

Reputation:

The DefaultModelBinder cannot initialize an instance or your Error class based on the query string parameters because you have private set on all your properties.

Your model should be

public class Error
{
  public String name {  get; set; }
  public String description {  get; set; }
  public int number {  get; set; }

  public Error() // you must add a parameter-less constructor
  {
  }

  public Error(String name, String description)
  {
    this.name = name;
    this.description = description;
    // number = 0; // no need for this - the default is 0
  }
}

You can also use

return RedirectToAction("Error","Home", new { name = "ErrorName", description = "ErrorDescription"});

and delete both constructors

Upvotes: 6

Timon
Timon

Reputation: 1013

Try using "error" in lower case when you name the anonymous parameter.

return RedirectToAction("Error","Home", new { error = (new Error("ErrorName","ErrorDescription"))} );

I believe the parameters are passed by name, and now he can't link "Error" to parameter name of your method.

Upvotes: 0

Related Questions