Asp mvc http get action with object as parameter

In my controller, I got the action:

[HttpGet] public ActionResult CreateAdmin(object routeValues = null) { //some code return View(); } 

And the http message:

 [HttpPost] public ActionResult CreateAdmin( string email, string nameF, string nameL, string nameM) { if (email == "" || nameF == "" || nameL == "" || nameM == "") { return RedirectToAction("CreateAdmin", new { error = true, email = email, nameF = nameF, nameL = nameL, nameM = nameM, }); } 

the routeValues ​​variable in http get Action always empty. How to pass an object as a parameter in [http get] Action ?

+4
source share
3 answers

You cannot pass a GET object; instead, try passing individual values ​​as follows:

 [HttpGet] public ActionResult CreateAdmin(int value1, string value2, string value3) { //some code var obj = new MyObject {property1 = value1; propety2 = value2; property3 = value3}; return View(); } 

Then you can pass values ​​from anywhere in your application, for example:

 http://someurl.com/CreateAdmin?valu1=1&value2="hello"&value3="world" 
+7
source

As already mentioned, you cannot pass an entire object to an HTTPGET action. However, what I like to do when I do not want to have an action with hundreds of parameters is the following:

  • Create a class that will encapsulate all the necessary parameters
  • Pass the string value to my HTTPGET action
  • Convert string parameter to actual object that is used by my GET action.

So, let's say you have this class representing all of your input fields:

  public class AdminContract { public string email {get;set;} public string nameF {get;set;} public string nameL {get;set;} public string nameM {get;set;} } 

Then you can add a GET action that only one, string parameter will expect:

 [HttpGet] public ActionResult GetAdmin(string jsonData) { //Convert your string parameter into your complext object var model = JsonConvert.DeserializeObject<AdminContract>(jsonData); //And now do whatever you want with the object var mail = model.email; var fullname = model.nameL + " " + model.nameF; // .. etc. etc. return Json(fullname, JsonRequestBehavior.AllowGet); } 

And tada! Just by string and object (at the front end), and then converting it (at the end), you can still take advantage of the HTTPGET request by passing the entire object in the request, rather than using dozens of parameters.

+2
source

You can pass values ​​to the Http Get method, for example

 Html.Action("ActionName","ControllerName",new {para1=value, para2 = value}); 

and you can define your action in the controller, for example

 [HtttpGet] public ActionResult ActionName(Para1Type para1, Para2Type para2) { } 
0
source

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


All Articles