Post multiple parameters to MVC Controller using C#

前端 未结 2 951
星月不相逢
星月不相逢 2020-12-19 14:00

I am posting a json object to an ASP.Net MVC controller with C# code. To keep things simple in this example the object is just a car with make and model properties. Everythi

相关标签:
2条回答
  • 2020-12-19 14:43

    Like this:

    string requestData = "{\"c\": {\"Make\":\"Ford\",\"Model\":\"Mustang\"}, \"email\": \"foo@bar.com\", \"phone\": \"1111\"}";
    

    Or even better using a JavascriptSerializer:

    using System;
    using System.Net;
    using System.Text;
    using System.Web.Script.Serialization;
    
    class Program
    {
        static void Main()
        {
            var serializer = new JavaScriptSerializer();
            string requestData = serializer.Serialize(new
            {
                c = new
                {
                    make = "Ford",
                    model = "Mustang"
                },
                email = "foo@bar.com",
                phone = "1111"
            });
    
            using (var client = new WebClient())
            {
                client.Headers[HttpRequestHeader.ContentType] = "application/json";
                var result = client.UploadData("http://receiving.url/showdata", Encoding.UTF8.GetBytes(requestData));
                Console.WriteLine(Encoding.UTF8.GetString(result));
            }
        }
    }
    

    which will take care of properly JSON serializing your object as if you are using those string concatenations your request might break easily if the data contains some special characters.

    Oh, and before I forget: use view models.

    So instead of:

    [HttpPost]
    public JsonResult showdata(Car c, string email, string phone)
    {
        ...
    }
    

    you should definitely be having:

    [HttpPost]
    public ActionResult ShowData(ShowDataViewModel data)
    {
        ...
    }
    

    and then:

    string requestData = serializer.Serialize(new
    {
        make = "Ford",
        model = "Mustang",
        email = "foo@bar.com",
        phone = "1111"
    });
    

    And another remark: you don't need JsonRequestBehavior.AllowGet when returning your JSON as you have decorated your controller action with [HttpPost] so this action can never be invoked with a GET verb.

    0 讨论(0)
  • 2020-12-19 14:53

    It is not a problem, make you request like:

    "{\"Make\":\"Ford\",\"Model\":\"Mustang\", \"email\":\"xxx\", \"phone\":\"yyy\" }";
    

    ASP.NET MVC Json binder should be smart enought to bing that correctly for method, like:

    public JsonResult showdata(Car c, string email, string phone)
    
    0 讨论(0)
提交回复
热议问题