简体   繁体   中英

Passing string from AJAX to C# code behind

I've looked at so many comments on this subject, and I have tried a number of suggested methods for accomplishing this but I'm still not able to access the code behind. Error message comes back with the success routine. I am using a Select2 as an input source (there is no list, only what the operator desires to enter) for multiple entries to be passed via ajax to my code behind. I believe the data type may not be the same as the code behind but not sure how to define it other than what I have, or has it been depracated and I am not aware. I changed to the original programming when the error occurred. myData is changed to model to match code behind. Here is what I get in the select2 if I put in "test" and "copy".

After model value is: test,copy

Here is my Client side code:

...
<select id="SearchSelect" style="width: 150px" name="SearchSelct" 
multiple onmouseover="SearchTip('#SrchToolTip','#hdnviewsrch');return 
false;"></select>
    <textarea id="SrchToolTip" style="color:blue" hidden="hidden">You can 
enter any keyword you like.</textarea>
    <br />
    <br />
<asp:Button ID="SearchFnd" runat="server" Text="Submit" 
OnClientClick="SearchSel('#SearchSelect');return false;" 
ValidateRequestMode="Disabled" UseSubmitBehavior="False"/>

<script type="text/javascript">
    $(document).ready(function () {
    //On client side - Here we render the Select 2
    $("#SearchSelect").select2(
    {
        placeholder: "Enter Search Parameters",
        tags: true,  
        tokenSeparators: [','], 
        allowClear: true,  
        minimumInputLength: 1,  
        width: 'resolve',   
        });
    });
    $("#SearchSelect").on("change", function (e) { 
SearchChange("SearchSelect"); });

    function SearchTip(SrchElem) {
        $(SrchElem).show();
        console.log("Search Tip value is: " + $("#SearchSelect").val());
        };

    function SearchChange(name, evt) {
        console.log("Search Change value is: " + $("#SearchSelect").val() 
+ "; Name: " + name);
    };
    function SearchSel(SchElem) {
        var model= { "SrchData": $(SchElem).val() };
        $.ajax(
        {
            type: "POST",    
            url: '<%= ResolveUrl("~/Default.aspx/SearchFind") %>', 
            data: JSON.stringify(model.SrchData),
            dataType: 'json',
            contentType: "application/json; charset=utf-8", 
            success: function (result) {
                alert('success');
                console.log("Search data obtained: " + result);
            },

            error: function (jqXHR, textStatus, errorThrown) {
                alert("error: " + errorThrown);
            },
            failure: function () {
            alert('Failure');
            }
            processResults: function (data, params) {
                console.log("Search data obtained: " + data);
                return {
                    results: data.d,
                    pagination: {
                        more: data.more
                    }

                };
             }
        });
    }
    </script>

Here is the code behind:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.Web.Script.Services;

namespace WebApplication2
{
  public partial class _Default : Page
  {
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    public class Schdata
    {
        public string SrchData { get; set; }
    }

    [WebMethod()]
    //  [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public static string SearchFind(Schdata model)
    {
        System.Diagnostics.Debug.WriteLine("Went into the SearchFind 
        subroutine " + model.SrchData);
        return "1";
        }

    }
}

Here is the error message:

success! {"Message":"Authentication failed.","StackTrace":null,"ExceptionType":"System.InvalidOperationException"}

The program says it is successful but gives an error that the value is null being returned (or sent) but on the code behind I have a breakpoint at the System.Diagnostics.Debug.WriteLine... line and it never reaches there. Any help would be appreciated.

In your code behind

public partial class _Default : Page
{
   string myStrCb = "Value from back";
   protected void Page_Load(object sender, EventArgs e)
   {
     //... any code
   }
   // ...more code
}

In your front code

<script>
  var myJsVar = <%=myStrCb %>
</script>

Use in script

function WriteValue()
{
  console.log(myJsVar); // Value from back
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM