如何在C#中的POST方法中发送FormCollection?

时间:2017-05-25 16:31:25

标签: c# asp.net-mvc

这是我的代码,但我只发送String,如何更改它以发送FormCollection?

public String peticionUrlPost_2(String url, FormCollection parametro)
{
HttpWebRequest HttpWRequest = (HttpWebRequest)WebRequest.Create(url);
HttpWRequest.Credentials = CredentialCache.DefaultCredentials;
HttpWRequest.Headers.Set("Pragma", "no-cache");
HttpWRequest.Timeout = 300000;
HttpWRequest.Method = "POST";
HttpWRequest.ContentType = "application/x-www-form-urlencoded";

byte[] PostData = System.Text.Encoding.ASCII.GetBytes(parametro);

HttpWRequest.ContentLength = PostData.Length;
Stream tempStream = HttpWRequest.GetRequestStream();
tempStream.Write(PostData, 0, PostData.Length);

HttpWebResponse response = (HttpWebResponse)HttpWRequest.GetResponse();
Stream receiveStream = response.GetResponseStream();

StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
String respuesta = readStream.ReadToEnd();
tempStream.Close();

return respuesta;

}

1 个答案:

答案 0 :(得分:1)

它实际上很简单,如果您使用下面的剃刀视图引擎就是示例:

@using (Html.BeginForm("peticionUrlPost_2", "AnyControllerName", FormMethod.Post))
{

    //Your all form fields like below
    @Html.TextBoxFor(m => m.StringData)
    @Html.CheckBoxFor(model => model.data)
    @Html.TextBoxFor(model => model.Data)

    <input type="submit" value="Submit strongly type synchronous form" />
}

有用的链接:https://www.aspsnippets.com/Articles/ASPNet-MVC-Form-Submit-Post-example.aspx

希望以上信息有用,请让我知道您的想法或反馈

由于

KARTHIK