asp mvc http get action with object as parameter

前端 未结 3 2048
慢半拍i
慢半拍i 2021-01-05 09:06

In my controller I got action:

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

相关标签:
3条回答
  • 2021-01-05 09:38

    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)
    {
    }
    
    0 讨论(0)
  • 2021-01-05 09:47

    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"
    
    0 讨论(0)
  • 2021-01-05 09:50

    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.

    0 讨论(0)
提交回复
热议问题