发布多个参数MVC控制器使用C# [英] Post multiple parameters to MVC Controller using C#

查看:149
本文介绍了发布多个参数MVC控制器使用C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我张贴的JSON对象到一个ASP.Net MVC控制器C#code。为了简单起见,在这个例子中,对象只是与品牌和型号性能的汽车。一切都与下面的code效果很好。我的问题是 - 我怎么会发布多个参数?例如,我怎么会发布一个JSON对象,电子邮件地址和电话号码吗?

  //后形成
    字符串的RequestData ={\\制作\\:\\福特\\,\\型号\\:\\野马\\};
    字节[]数据= Encoding.UTF8.GetBytes(的RequestData);
    HttpWebRequest的要求=(HttpWebRequest的)WebRequest.Create(HTTP://receiving.url/showdata);
    request.Method =POST;
    request.ContentType =应用/ JSON;
    流数据流= request.GetRequestStream();
    dataStream.Write(数据,0,data.Length);
    dataStream.Close();    WebResponse的响应= request.GetResponse();
    字符串结果=新的StreamReader(response.GetResponseStream())为ReadToEnd()。
    Console.Write(结果);

下面是控制器code检索从帖子JSON对象,然后输出进行验证的JSON。

  [HttpPost]
    公共JsonResult showdata(轿车三)
    {
        返回JSON(C,JsonRequestBehavior.AllowGet);
    }

我希望做这样的事情:

  [HttpPost]
    公共JsonResult showdata(车载C,字符串email,字符串电话)
    {        返回JSON(C,JsonRequestBehavior.AllowGet);
    }


解决方案

这样的:

 字符串的RequestData ={\\C:\\:{\\制作\\:\\福特\\,\\型号\\:\\野马\\} \\ 电子邮件\\:\\foo@bar.com \\,\\电话\\:\\1111 \\};

甚至更好使用<一个href=\"http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx\">JavascriptSerializer:

 使用系统;
使用System.Net;
使用System.Text;
使用System.Web.Script.Serialization;类节目
{
    静态无效的主要()
    {
        VAR串行=新的JavaScriptSerializer();
        字符串=的RequestData serializer.Serialize(新
        {
            C =新
            {
                令=福特,
                模型=野马
            },
            电子邮件=foo@bar.com
            手机=1111
        });        使用(VAR的客户=新的WebClient())
        {
            client.Headers [Htt的prequestHeader.ContentType] =应用/ JSON;
            VAR的结果= client.UploadData(HTTP://receiving.url/showdata,Encoding.UTF8.GetBytes(的RequestData));
            Console.WriteLine(Encoding.UTF8.GetString(结果));
        }
    }
}

将采取妥善JSON序列化你的对象,如果你正在使用这些字符串连接,如果该数据包含一些特殊字符,您的请求可能会轻松突破照顾。

哦,我忘了之前:使用视图模型

所以

而不是:

  [HttpPost]
公共JsonResult showdata(车载C,字符串email,字符串电话)
{
    ...
}

您绝对应该有:

  [HttpPost]
公众的ActionResult ShowData(ShowDataViewModel数据)
{
    ...
}

和则:

 字符串=的RequestData serializer.Serialize(新
{
    令=福特,
    模型=野马,
    电子邮件=foo@bar.com
    手机=1111
});

和其他备注:您不必 JsonRequestBehavior.AllowGet 返回您JSON作为时,你装饰了你的控制器行动 [HttpPost] 所以这个动作可以永远使用GET动词调用。

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. Everything works well with the code below. My question is - how would I post multiple parameters? For example, how would I post a JSON object, an email address, and a phone number?

    //post to form
    string requestData = "{\"Make\":\"Ford\",\"Model\":\"Mustang\"}";
    byte[] data = Encoding.UTF8.GetBytes(requestData);
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://receiving.url/showdata");
    request.Method = "POST";
    request.ContentType = "application/json";
    Stream dataStream = request.GetRequestStream();
    dataStream.Write(data, 0, data.Length);
    dataStream.Close();

    WebResponse response = request.GetResponse();
    string result = new StreamReader(response.GetResponseStream()).ReadToEnd();
    Console.Write(result);

Here is the Controller code that retrieves the json object from the post, and then outputs the json for verification purposes.

    [HttpPost]
    public JsonResult showdata(Car c)
    {
        return Json(c, JsonRequestBehavior.AllowGet);
    }

I'm looking to do something like this:

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

        return Json(c, JsonRequestBehavior.AllowGet);
    }

解决方案

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.

这篇关于发布多个参数MVC控制器使用C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆