Проблема с отправкой данных строкового типа в веб-форме asp.net и Ajax - PullRequest
0 голосов
/ 16 декабря 2018

Я написал код, с помощью которого я могу легко работать на страницах, отличных от страницы поиска.Все параметры для базы данных, C # и Ajax определены в виде чисел.

На странице поиска, помимо числовых параметров, мне нужен параметр типа строки для перевода поискового запроса.

Когда я передаю фразу «2», программа работает правильно.

Но когда я передаю в программу строку типа «a», при прокрутке страницы программа выдаст ошибку.

Я пробовал много способов, но я не получил никаких результатов.

Спасибо.

My Global:

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");
}

Моя search.aspx разметка страницы:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="http://localhost:4295/css/site.css" rel="stylesheet" />
    <link href="http://localhost:4295/css/bootstrap.min.css" rel="stylesheet" />
    <link rel="stylesheet" type="text/css" href="http://localhost:4295/css/bootstrap-drilldown-select.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="http://localhost:4295/js/bootstrap.min.js"></script>
    <script>
        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();
            });
        });
    </script>
    <script type="text/javascript">
        var pageIndex = 1;
        var pageCount;
        $(window).scroll(function () {
            if ($(window).scrollTop() == $(document).height() - $(window).height()) {
                if ($('#<%= ddlCity.ClientID %>').val() == "1") {

                    GetRecords1();
                }
                else {
                    GetRecords();
                }

            }
        });
        function GetRecords() {
            pageIndex++;
            if (pageIndex == 2 || pageIndex <= pageCount) {
                $("#loader").show();
                $.ajax({
                    type: "POST",
                    url: "http://localhost:4295/search/default.aspx/GetCustomers",
                    data: '{pageIndex: ' + pageIndex + ',city: ' +<%= Variable_codebehind %> + ',item: ' +JSON.stringify(<%= Variable_codebehind1 %>) +'}',
                    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 <= pageCount) {
                $("#loader").show();
                $.ajax({
                    type: "POST",
                    url: "http://localhost:4295/search/default.aspx/GetCustomers1",
                    data: '{pageIndex: ' + pageIndex + ',item:' + JSON.stringify(<%= Variable_codebehind1 %>) + '}',
                    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();
        }
</script>

    <script src="http://localhost:4295/js/jquery-ui.min.js"></script>
    <link href="http://localhost:4295/css/jquery-ui.css" rel="stylesheet" />
<script type="text/javascript">
    $(function () {
        $("[id$=txtSearcher]").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: '<%=ResolveUrl("~/default1.aspx/GetSaerch") %>',
                    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
        });
    });
</script>
</head>

Мой Search.aspx.cs код:

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 < 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<string> customers = new List<string>();

            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();
        }
    }
}

Мой SQL:

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

Скриншот ошибки, которую я получаю:

enterописание изображения здесь

1 Ответ

0 голосов
/ 16 декабря 2018

Я решил.

замените код ниже

function GetRecords1() {
            pageIndex++;
            if (pageIndex == 2 || pageIndex <= pageCount) {
                $("#loader").show();
                $.ajax({
                    type: "POST",
                    url: "http://localhost:4295/search/default.aspx/GetCustomers1",
                    data: '{pageIndex: ' + pageIndex + ',item:' + JSON.stringify(<%= Variable_codebehind1 %>) + '}',
                    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 <= pageCount) {
                $("#loader").show();
                var ada = { 'pageIndex': pageIndex, 'item': $("[id$=txtSearcher]").val() }
                $.ajax({
                    type: "POST",
                    url: "http://localhost:4295/search/default.aspx/GetCustomers1",
                    data: JSON.stringify(ada),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: OnSuccess,
                    failure: function (response) {
                        alert(response.d);
                    },
                    error: function (response) {
                        alert(response.d);
                    }
                });
            }
        }

Спасибо stackoverflow;)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...