C#提交http发布请求以填写表格

时间:2018-07-26 18:02:16

标签: javascript c# forms http

我正在尝试使用C#向我的网站提交表单。在我的网站上,我有一个请愿表,其中有几个文本框和一个提交按钮,我可以在浏览器上完全正常地执行此操作,但是我想从C#中执行此操作。 这是以下非常简单的javascript代码:

(function($) {
"use strict";

var $button = $('#sign-petition');

$button.submit(function(e){
    e.preventDefault();

    var $country = '';
    var $state = '';
    var $zip = '';
    var $city = '';
    var $terms = '';
    var $newsletter = 0;
    var $bio = '';

    if( $( 'select[name="country"]', this ).length > 0 ) {
        $country = $( 'select[name="country"]', this ).val();
    }

    if( $( 'input[name="state"]', this ).length > 0 ) {
        $state = $( 'input[name="state"]', this ).val();
    }

    if( $( 'input[name="zip"]', this ).length > 0 ) {
        $zip = $( 'input[name="zip"]', this ).val();
    }

    if( $( 'input[name="city"]', this ).length > 0 ) {
        $city = $( 'input[name="city"]', this ).val();
    }

    if( $( 'input[name="terms"]', this ).length > 0 ) {
        if( $( 'input[name="terms"]', this ).prop('checked') ){
            $terms = $( 'input[name="terms"]', this ).val();
        }
    }

    if( $( 'input[name="newsletter"]', this ).length > 0 ) {
        if( $( 'input[name="newsletter"]', this ).prop('checked') ){
            $newsletter = 1;
        }
    }

    if( $( 'textarea.bio', this ).length > 0 ) {
        $bio = $( 'textarea.bio', this ).val();
    }

    var data = {
        'action': 'sign_petition',
        'email' : $( 'input[name="email"]', this ).val(),
        'fname' : $( 'input[name="fname"]', this ).val(),
        'lname' : $( 'input[name="lname"]', this ).val(),
        'bio'   : $bio,
        'signature' : $( '#signature', this ).val(),
        'country' : $country,
        'state' : $state,
        'zip'   : $zip,
        'city'  : $city,
        'terms' : $terms,
        'newsletter' : $newsletter
    };

    $.post( petition.ajaxurl, data, function( response ) {
        //console.log(response);
        response = JSON.parse(response);

        if( typeof(response.errors) !== "undefined" && response.errors !== null ){

            if( $( '#petition-errors' ).html() !== '' ){ $( '#petition-errors' ).html(''); }

            $('#sign-petition .error').each(function (){
                $(this).removeClass('error');
            });

            $.each( response.errors, function( key, error ){
                $( '.' + key, '#sign-petition' ).addClass( 'error' );
                $( '#petition-errors' ).append( '<li>' + error[0] + '</li>' );
            });
        } else{
            $( '<p>' + response.success + '</p>' ).insertBefore( '#sign-petition' );
            $('#sign-petition').hide();
        }

    });

});


})(jQuery);

我已经使用了Microsoft提供的示例,到目前为止,这是我所拥有的,但是它无法正常工作。

        string uriString = "https://example.org/";

        // Create a new WebClient instance.
        WebClient myWebClient = new WebClient();

        // Create a new NameValueCollection instance to hold some custom parameters to be posted to the URL.
        NameValueCollection myNameValueCollection = new NameValueCollection();

        myNameValueCollection.Add("signature", "15c8c9a392");
        myNameValueCollection.Add("email", "tom@appleseed.com");
        myNameValueCollection.Add("fname", "Tom");
        myNameValueCollection.Add("lname", "Appleseed");
        myNameValueCollection.Add("country", "US");
        myNameValueCollection.Add("state", "WA");
        myNameValueCollection.Add("zip", "98174");
        myNameValueCollection.Add("city", "Seattle");


        var responseArray = myWebClient.UploadValues(uriString, myNameValueCollection);
        var response = Encoding.ASCII.GetString(responseArray);
        var outputFilePath = Environment.CurrentDirectory + "\\petition\\" + DateTime.Now.ToString("yyyy-MM-dd--HH-mm-ss") + ".html";
        try
        {
            File.WriteAllText(outputFilePath, response);
        }
        catch (Exception e) { Console.WriteLine(e); }

这也是html代码:

    <form id="sign-petition" method="post">
        <input type="hidden" id="signature" name="signature" value="15c8c9a392"> 
         <input type="hidden" name="_wp_http_referer" value="/">

         <div class="form-group">
             <input type="text" class="form-control email" name="email" value="" placeholder="E-mail Address"">
         </div>

         <div class="form-group">
             <input type="text" class="form-control fname" name="fname" value="" placeholder="First Name">
         </div>

         <div class="form-group">
             <input type="text" class="form-control lname" name="lname" value="" placeholder="Last Name">
         </div>

         <div class="form-group">
             <select name="country" class="form-control" id="country">
                 <option value="0" selected="selected">Select a country ... </option>
                 <option value="US" label="United States">United States</option>
             </select>
         </div>

         <div class="form-group">
             <input type="text" class="form-control lname" name="state" value="" placeholder="State / Province">
         </div>

         <div class="form-group">
             <input type="text" class="form-control lname" name="zip" value="" placeholder="Zip / Postal Code">
         </div>

         <div class="form-group">
             <input type="text" class="form-control lname" name="city" value="" placeholder="City">
         </div>

         <div class="form-group">
             <textarea class="form-control bio" placeholder="comments" rows="3"></textarea>
         </div>

         <ul id="petition-errors"></ul>
         <button type="submit" class="btn btn-primary">Sign Petition!</button>
</form>

感谢任何帮助 谢谢。

1 个答案:

答案 0 :(得分:1)

使用HttpClient并发布数据该怎么办?像这样的东西。

var data = new
{
    action = "sign_petition",
    signature = "15c8c9a392",
    email = "tom.appleseed.com",
    fname = "Tom",
    lname = "Appleseed",
    country = "US",
    state = "WA",
    zip = "98174",
    city = "Seattle"
};
using (var client = new HttpClient())
{
    var uriString = "https://example.org";
    var result = client.PostAsync(uriString, new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json")).Result;
    if (!result.IsSuccessStatusCode)
    {
        //Handle the error
    }
    else
    {
        //Do something else
    }
}