In my controller I got action:
[HttpGet]
public ActionResult CreateAdmin(object routeValues = null)
{
//some code
return View();
}
And http post:
[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,
});
}
variable routeValues in http get Action is always empty. How correctly pass object as parameter to [http get] Action?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You cannot pass an object to GET, instead try passing individual values like this:
[HttpGet]
public ActionResult CreateAdmin(int value1, string value2, string value3)
{
//some code
var obj = new MyObject {property1 = value1; propety2 = value2; property3 = value3};
return View();
}
You can then pass values from anywhere of your app like:
http://someurl.com/CreateAdmin?valu1=1&value2="hello"&value3="world"
Method 2
As previously 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:
- Create a class that will encapsulate all the required parameters
- Pass a string value to my HTTPGET action
- Convert the string parameter to the actual object that my GET action is using.
Thus, say you have this class representing all 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;}
}
You can then add a GET Action that will expect only one, string parameter:
[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 stringifying and object (on the front end) and then converting it (in the back end) you can still enjoy the benefits of the HTTPGET request while passing an entire object in the request instead of using tens of parameters.
Method 3
You can pass values to a Http Get method like
Html.Action("ActionName","ControllerName",new {para1=value, para2 = value});
and you can have your action defined in the controller like
[HtttpGet]
public ActionResult ActionName(Para1Type para1, Para2Type para2)
{
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0