RedirectToAction to another controller and transfer parameters

I am new to C # and espacially in ASP.NET MVC.

I have my HomeController that contains this method:

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

Now I have another controller that has the following line inside:

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

As you may have noticed, I'm trying to pass an Error object to another controller, which then needs to pass it to the view.

The error class that I wrote myself is nothing impressive:

 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 is that every time I try to access the Variable variable in the HomeController, it is null . I already found google to search for posts, but I don’t understand why my code is not working. No errors, only this object with a zero value. I appreciate any help! :)

+6
source share
3 answers

DefaultModelBinder cannot initialize an instance or your Error class based on query string parameters, since you have a private set for all of 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 remove both constructors

+6
source

Try using a lowercase "error" when you name an anonymous parameter.

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

I believe that the parameters are passed by name, and now it cannot associate "Error" with the parameter name of your method.

0
source

You cannot pass complex objects in a url. You will have to send your components:

 public ActionResult YourAction() { // Here user object with updated data return RedirectToAction("Error","Home", new { name = "ErrorName", description = "ErrorDescription", number = 0 }); } 
0
source

Source: https://habr.com/ru/post/988847/


All Articles