title: Problem with sending string type data in asp.net web form and Ajax
body: <p>I have written code that I can easily work on pages other than the search page.
  All parameters for the database, C#, and Ajax are defined as numbers.</p>
  
  <p>In the search page, in addition to the numerical parameters, I need a parameter of the string type to translate the search term.</p>
  
  <p>When I transfer phrase "2", the program works correctly.</p>
  
  <p>But when I transfer a string like "a" to a program, the program will error when scrolling the page.</p>
  
  <p>I tried many ways but I did not get any results.</p>
  
  <p>Thanks.</p>
  
  <p>My Global :</p>
  
  <pre><code>public static void RegisterRoutes(RouteCollection routes)
  {
              routes.Ignore("{resource}.axd/{*pathInfo}");
  
              routes.MapPageRoute("search", "search/{citName}/{searchitem}", "~/search/default.aspx");
              routes.MapPageRoute("edit", "edit-{alphabetID}", "~/manage/edit.aspx");
              routes.MapPageRoute("manage", "manage-{alphabetID}", "~/manage/default.aspx");
              routes.MapPageRoute("daste", "browse/{citName}/{mainName}/{secName}/{dasteName}", "~/daste.aspx");
              routes.MapPageRoute("sec", "browse/{citName}/{mainName}/{secName}", "~/sec.aspx");
              routes.MapPageRoute("base", "browse/{citName}", "~/default1.aspx");
              routes.MapPageRoute("main", "browse/{citName}/{mainName}", "~/main.aspx");
              routes.MapPageRoute("end", "ads/{alphabetID}/{adsName}", "~/end.aspx");
  }
  </code></pre>
  
  <p>My <code>search.aspx</code> page markup:</p>
  
  <pre><code>&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
  &lt;head runat="server"&gt;
      &lt;title&gt;&lt;/title&gt;
      &lt;meta charset="utf-8"&gt;
      &lt;meta name="viewport" content="width=device-width, initial-scale=1"&gt;
      &lt;link href="http://localhost:4295/css/site.css" rel="stylesheet" /&gt;
      &lt;link href="http://localhost:4295/css/bootstrap.min.css" rel="stylesheet" /&gt;
      &lt;link rel="stylesheet" type="text/css" href="http://localhost:4295/css/bootstrap-drilldown-select.css"&gt;
      &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt;
      &lt;script src="http://localhost:4295/js/bootstrap.min.js"&gt;&lt;/script&gt;
      &lt;script&gt;
          jQuery(document).ready(function () {
              jQuery('.toggle-nav').click(function (e) {
                  jQuery(this).toggleClass('active');
                  jQuery('.menu ul').toggleClass('active');
  
                  e.preventDefault();
              });
  
          });
          $(function () {
              $('a.disactive').on("click", function (e) {
                  e.preventDefault();
              });
          });
      &lt;/script&gt;
      &lt;script type="text/javascript"&gt;
          var pageIndex = 1;
          var pageCount;
          $(window).scroll(function () {
              if ($(window).scrollTop() == $(document).height() - $(window).height()) {
                  if ($('#&lt;%= ddlCity.ClientID %&gt;').val() == "1") {
  
                      GetRecords1();
                  }
                  else {
                      GetRecords();
                  }
  
              }
          });
          function GetRecords() {
              pageIndex++;
              if (pageIndex == 2 || pageIndex &lt;= pageCount) {
                  $("#loader").show();
                  $.ajax({
                      type: "POST",
                      url: "http://localhost:4295/search/default.aspx/GetCustomers",
                      data: '{pageIndex: ' + pageIndex + ',city: ' +&lt;%= Variable_codebehind %&gt; + ',item: ' +JSON.stringify(&lt;%= Variable_codebehind1 %&gt;) +'}',
                      contentType: "application/json; charset=utf-8",
                      dataType: "json",
                      success: OnSuccess,
                      failure: function (response) {
                          alert(response.d);
                      },
                      error: function (response) {
                          alert(response.d);
                      }
                  });
              }
          }
          function GetRecords1() {
              pageIndex++;
              if (pageIndex == 2 || pageIndex &lt;= pageCount) {
                  $("#loader").show();
                  $.ajax({
                      type: "POST",
                      url: "http://localhost:4295/search/default.aspx/GetCustomers1",
                      data: '{pageIndex: ' + pageIndex + ',item:' + JSON.stringify(&lt;%= Variable_codebehind1 %&gt;) + '}',
                      contentType: "application/json; charset=utf-8",
                      dataType: "json",
                      success: OnSuccess,
                      failure: function (response) {
                          alert(response.d);
                      },
                      error: function (response) {
                          alert(response.d);
                      }
                  });
              }
          }
          function OnSuccess(response) {
              var xmlDoc = $.parseXML(response.d);
              var xml = $(xmlDoc);
              pageCount = parseInt(xml.find("PageCount").eq(0).find("PageCount").text());
              var customers = xml.find("T_AddBarg");
              customers.each(function () {
                  var customer = $(this);
                  var table = $("#dvCustomers .col-md-4").eq(0).clone(true);
                  $("a.qwqw", table).attr('href', 'http://localhost:4295/ads/' + customer.find("BargAlphabetID").text() + '/' + customer.find("BargTitle").text().toString().replace(/\s+/g, '-'));
                  $(".mmatn", table).html(customer.find("BargTitle").text());
                  $(".dast", table).html(customer.find("BargDasteName").text());
                  $(".def", table).html(customer.find("ddd").text());
                  $(".immmg", table).attr('src', 'http://localhost:4295/pic-bag/' + customer.find("BargPic").text());
                  $(".price", table).html(customer.find("BargPrice").text());
                  $("#dvCustomers").append(table);
  
  
              });
              $("#loader").hide();
          }
  &lt;/script&gt;
  
      &lt;script src="http://localhost:4295/js/jquery-ui.min.js"&gt;&lt;/script&gt;
      &lt;link href="http://localhost:4295/css/jquery-ui.css" rel="stylesheet" /&gt;
  &lt;script type="text/javascript"&gt;
      $(function () {
          $("[id$=txtSearcher]").autocomplete({
              source: function (request, response) {
                  $.ajax({
                      url: '&lt;%=ResolveUrl("~/default1.aspx/GetSaerch") %&gt;',
                      data: "{ 'prefix': '" + request.term + "'}",
                      dataType: "json",
                      type: "POST",
                      contentType: "application/json; charset=utf-8",
                      success: function (data) {
                          response($.map(data.d, function (item) {
                              return {
                                  label: item.split('-')[0],
                                  val: item.split('-')[1]
                              }
                          }))
                      },
                      error: function (response) {
                          alert(response.responseText);
                      },
                      failure: function (response) {
                          alert(response.responseText);
                      }
                  });
              },
              select: function (e, i) {
                  $("[id$=hfCustomerId]").val(i.item.val);
              },
              minLength: 1
          });
      });
  &lt;/script&gt;
  &lt;/head&gt;
  </code></pre>
  
  <p>My <code>Search.aspx.cs</code> code behind:</p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Configuration;
  using System.Data;
  using System.Data.SqlClient;
  using System.Linq;
  using System.Text;
  using System.Web;
  using System.Web.Services;
  using System.Web.UI;
  using System.Web.UI.WebControls;
  
  namespace MedBarg.search
  {
      public partial class _default : System.Web.UI.Page
      {
          protected string Variable_codebehind;
          protected string Variable_codebehind1;
          MedBargEntities context = new MedBargEntities();
  
          protected void Page_Load(object sender, EventArgs e)
          {
              if (!Page.IsPostBack)
              {
                  //FillAds();
                  getddlNewGroup();
                  string ss = Page.RouteData.Values["citName"].ToString().Replace("-", " ");
                  string tt = Page.RouteData.Values["searchitem"].ToString();
  
                  if (ss == "ایران")
                  {
                      //var res = (from c in context.T_AdsCity
                      //           where c.AdsCityName == ss
                      //           select c).First();
                      //Variable_codebehind = res.AdsCityID.ToString();
                      txtSearcher.Text = tt;
                      Variable_codebehind1 = tt.ToString();
                      MyRepeater.DataSource = GetCustomersData1(1, Variable_codebehind1);
                      MyRepeater.DataBind();
                  }
                  else
                  {
                      var res = (from c in context.T_AdsCity
                                 where c.AdsCityName == ss
                                 select c).First();
                      txtSearcher.Text = tt;
                      Variable_codebehind = res.AdsCityID.ToString();
                      Variable_codebehind1 = tt.ToString();
                      MyRepeater.DataSource = GetCustomersData(1, int.Parse(Variable_codebehind), Variable_codebehind1);
                      MyRepeater.DataBind();
                  }
  
              }
          }
  
          protected void getddlNewGroup()
          {
              ddlCity.Items.Clear();
              string strSQLconnection = ConfigurationManager.ConnectionStrings["MedBargConnectionString"].ConnectionString;
              SqlConnection sqlConnection = new SqlConnection(strSQLconnection);
              SqlCommand sqlCommand = new SqlCommand("select * from T_AdsCity", sqlConnection);
  
              sqlCommand.CommandType = CommandType.Text;
              sqlCommand.Connection = sqlConnection;
  
              try
              {
                  sqlConnection.Open();
                  ddlCity.DataSource = sqlCommand.ExecuteReader();
                  ddlCity.DataTextField = "AdsCityName";
                  ddlCity.DataValueField = "AdsCityID";
                  ddlCity.DataBind();
  
                  foreach (ListItem item in ddlCity.Items)
                  {
                      if (item.Text == getcit())
                      {
                          item.Selected = true;
                          //break;
                      }
                  }
              }
              catch (Exception)
              {
              }
              finally
              {
                  sqlConnection.Close();
                  sqlConnection.Dispose();
              }
          }
  
          public string getcit()
          {
              return Page.RouteData.Values["citName"].ToString().Replace("-", " ");
          }
  
          public void FillAds()
          {
              string ss = Page.RouteData.Values["citName"].ToString().Replace("-", " ");
  
              if (ss == "ایران")
              {
                  var res = (from c in context.T_AddBarg
                             join p in context.T_AdsCity on c.BargCityID equals p.AdsCityID
                             where c.BargStatus == 1
                             orderby c.BargDate descending
                             select new
                             {
                                 c.BargDate,
                                 c.BargID,
                                 c.BargText,
                                 c.BargTitle,
                                 c.BargPrice,
                                 p.AdsCityName,
                                 c.BargAlphabetID
                             }).ToList();
  
                  MyRepeater.DataSource = res;
                  MyRepeater.DataBind();
              }
              else
              {
                  var res = (from c in context.T_AddBarg
                             join p in context.T_AdsCity on c.BargCityID equals p.AdsCityID
                             where c.BargStatus == 1
                             where p.AdsCityName == ss
                             orderby c.BargDate descending
                             select new
                             {
                                 c.BargDate,
                                 c.BargID,
                                 c.BargText,
                                 c.BargTitle,
                                 c.BargPrice,
                                 p.AdsCityName,
                                 c.BargAlphabetID
                             }).ToList();
  
                  MyRepeater.DataSource = res;
                  MyRepeater.DataBind();
              }
  
          }
  
          protected void ddlCity_SelectedIndexChanged(object sender, EventArgs e)
          {
              System.Web.HttpContext contextcart = System.Web.HttpContext.Current;
  
              if (contextcart.Request.Cookies["hugecook"] != null)
              {
                  string[] aa = contextcart.Request.Cookies["hugecook"].Value.ToString().Split('*');
                  //int aaa = int.Parse(aa[0].ToString());
                  //var res = (from c in context.T_AdsCity
                  //           where c.AdsCityID == aaa
                  //           select c).First();
                  aa[0] = ddlCity.SelectedValue;
                  HttpCookie AbarlabCookies = new HttpCookie("hugecook");
  
                  var sb = new StringBuilder();
  
                  for (int i = 0; i &lt; 3; i++)
                  {
                      sb.Append(aa[i] + "*");
  
                      if (i == 2)
                      {
                          sb.Append(aa[i]);
                      }
                  }
  
                  AbarlabCookies.Value = sb.ToString();
                  AbarlabCookies.Expires = DateTime.Now.AddDays(7);
                  Response.Cookies.Add(AbarlabCookies);
                  Response.Redirect("http://localhost:4295/browse/" + ddlCity.SelectedItem.Text.ToString().Replace(" ", "-"));
              }
  
              //Response.Redirect("http://localhost:4295/browse/"+ddlCity.SelectedItem.Text.ToString().Replace(" ","-"));
          }
  
          public static DataSet GetCustomersData(int pageIndex, int city, string item)
          {
              string query = "[GetCustomersPageWise51]";
              SqlCommand cmd = new SqlCommand(query);
              cmd.CommandType = CommandType.StoredProcedure;
              cmd.Parameters.AddWithValue("@PageIndex", pageIndex);
              cmd.Parameters.AddWithValue("@pageddd", city);
              cmd.Parameters.AddWithValue("@PageSize", 9);
              cmd.Parameters.AddWithValue("@pagetit", item);
              cmd.Parameters.Add("@PageCount", SqlDbType.Int, 4).Direction = ParameterDirection.Output;
              return GetData(cmd);
          }
  
          public static DataSet GetCustomersData1(int pageIndex, string item)
          {
              string query = "[GetCustomersPageWise52]";
              SqlCommand cmd = new SqlCommand(query);
              cmd.CommandType = CommandType.StoredProcedure;
              cmd.Parameters.AddWithValue("@PageIndex", pageIndex);
              //cmd.Parameters.AddWithValue("@pageddd", city);
              cmd.Parameters.AddWithValue("@PageSize", 9);
              cmd.Parameters.AddWithValue("@pagetit", item);
              cmd.Parameters.Add("@PageCount", SqlDbType.Int, 4).Direction = ParameterDirection.Output;
              return GetData(cmd);
          }
  
          private static DataSet GetData(SqlCommand cmd)
          {
              string strConnString = ConfigurationManager.ConnectionStrings["MedBargConnectionString"].ConnectionString;
              using (SqlConnection con = new SqlConnection(strConnString))
              {
                  using (SqlDataAdapter sda = new SqlDataAdapter())
                  {
                      cmd.Connection = con;
                      sda.SelectCommand = cmd;
                      using (DataSet ds = new DataSet())
                      {
                          sda.Fill(ds, "T_AddBarg");
                          DataTable dt = new DataTable("PageCount");
                          dt.Columns.Add("PageCount");
                          dt.Rows.Add();
                          dt.Rows[0][0] = cmd.Parameters["@PageCount"].Value;
                          ds.Tables.Add(dt);
                          return ds;
                      }
                  }
              }
          }
  
          [WebMethod]
          public static string GetCustomers(int pageIndex, int city, string item)
          {
              //string ss = Page.RouteData.Values["citName"].ToString().Replace("-", " ");
              return GetCustomersData(pageIndex, city, item).GetXml();
          }
  
          [WebMethod]
          public static string GetCustomers1(int pageIndex, string item)
          {
              //string ss = Page.RouteData.Values["citName"].ToString().Replace("-", " ");
              return GetCustomersData1(pageIndex, item).GetXml();
          }
  
          [WebMethod]
          public static string[] GetSaerch(string prefix)
          {
              List&lt;string&gt; customers = new List&lt;string&gt;();
  
              using (SqlConnection conn = new SqlConnection())
              {
                  conn.ConnectionString = ConfigurationManager.ConnectionStrings["MedBargConnectionString"].ConnectionString;
                  using (SqlCommand cmd = new SqlCommand())
                  {
                      cmd.CommandText = "select DasteID, DasteName from T_AdDaste where DasteName like @SearchText + '%'";
                      cmd.Parameters.AddWithValue("@SearchText", prefix);
                      cmd.Connection = conn;
                      conn.Open();
  
                      using (SqlDataReader sdr = cmd.ExecuteReader())
                      {
                          while (sdr.Read())
                          {
                              customers.Add(string.Format("{0}-{1}", sdr["DasteName"], sdr["DasteID"]));
                          }
                      }
                      conn.Close();
                  }
              }
              return customers.ToArray();
          }
      }
  }
  </code></pre>
  
  <p>My SQL :</p>
  
  <pre><code>SET ANSI_NULLS ON
  GO
  SET QUOTED_IDENTIFIER ON
  GO
  
  ALTER PROCEDURE [dbo].[GetCustomersPageWise51]
      @PageIndex INT = 1,
      @PageSize INT = 6,
      @pageddd INT,
      @pagetit NVARCHAR(100),
      @PageCount INT OUTPUT
  AS
  BEGIN
      SET NOCOUNT ON;
  
      SELECT 
          ROW_NUMBER() OVER (ORDER BY [BargID] DESC) AS RowNumber,
          [BargID],
          [BargAlphabetID],
          [BargTitle],
          [BargPrice],
          [BargDate],
          [BargCityID],
          [BargPic],
          [BargDasteName]
      INTO 
          #Results
      FROM
          [T_AddBarg] AS a
      INNER JOIN
          [T_AdDaste] AS b ON a.BargDasteID = b.DasteID
      WHERE
          a.BargCityID = @pageddd
          AND a.BargTitle LIKE '%' + @pagetit + '%'
      ORDER BY 
          BargID DESC
  
      DECLARE @RecordCount INT
  
      SELECT @RecordCount = COUNT(*) FROM #Results
  
      SET @PageCount = CEILING(CAST(@RecordCount AS DECIMAL(10, 2)) / CAST(@PageSize AS DECIMAL(10, 2)))
      PRINT @PageCount
  
      --SELECT BargID,BargDasteID,BargDasteName,BargTitle,BargDate,(datediff(MI, BargDate , GETDATE())) as ddd FROM #Results
      SELECT 
          BargDasteName, BargPic,
          BargCityID, BargID,
          BargAlphabetID, BargTitle,
          BargPrice, BargTitle,
          BargDate, 
          (dbo.MyScalarFunction(BargDate)) as ddd 
      FROM 
          #Results 
      WHERE 
          (RowNumber BETWEEN (@PageIndex -1) * @PageSize + 1 
                     AND (((@PageIndex -1) * @PageSize + 1) + @PageSize) - 1)
          --ANd BargCityID = 2
  
      DROP TABLE #Results
  END
  </code></pre>
  
  <p>Screenshot of the error I get:</p>
  
  <p><a href="https://i.stack.imgur.com/pZqKU.jpg" rel="nofollow noreferrer">enter image description here</a></p>