skip to Main Content

I’m newbie in asp.net webform. I have so many problems that’s almost I got solution from StackOverflow. But Now I’m facing an issue and can’t get any desired solution, So, I’m writing this question.
I want a textbox to autocomplete with JQuery autocomplete call. I have two textboxes, one is for autocomplete suggestion list, another is getting selected item Id. I don’t know how modern website do this. But fortunately, I got a hints by googling it.

Here I have create a codebehind [WebMethod] attribute Method:

// Class for Custom datatype object
public class MyData
{
    public int Id { get; set; }
    public string Value { get; set; }
}

// Webmethod for call from ajax
[WebMethod]
public static MyData GetDataList()
{
    int id = 123;
    string value = "My Name";
    return new MyData { Id = id, Value = value };
}

And here is my JQuery function.

$(function () {
    $("#autocomplete").autocomplete({
        source: function (request, response) {
            $.ajax({
                type: 'POST',
                url: 'reissue_ticket.aspx/GetDataList',
                data: '{ "term": "' + request.term + '" }',
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                success: function (data) {
                    response(data.d);
                },
                error: function () {
                    console.log('Error fetching items.');
                }
            });
        },
        minLength: 1,
        select: function (event, ui) {
            // Set the selected value and id into textboxes
            $('#selectedValue').val(ui.item.value);
            $('#selectedId').val(ui.item.id);
        }
    });
});

It’s work fine but problem is I got 3 object response. like:

json respose text

{
    "d": {
        "__type": "eLedger.com.Pages.Services.reissue_ticket+MyData",
        "Id": 123,
        "Value": "My Name"
    }
}

I don’t want"__type": "eLedger.com.Pages.Services.reissue_ticket+MyData". I tryed in c# like Json Serialized but nothing works.

Please someone help me to get this problem solve or any better idea with webform.

Thanks in advance for reading my problem at least.

I want the response like {"Id":1, "Value": "My Name"} only.

2

Answers


  1. Chosen as BEST ANSWER

    Thanks everyone for the reading, comments, and answer. I solve this problem in different ways with anonymous object method that works file with few efforts. here is my solution:

    public static object[] Airlines(string prefix)
    {
        string query = string.Format("SELECT AirlineID, AirlineName FROM airlines WHERE AirlineName LIKE CONCAT('%', @name, '%') OR AirlineCode= @code ");
        MySqlParameter param1 = new MySqlParameter("@name", prefix.Trim());
        MySqlParameter param2 = new MySqlParameter("@code", prefix.Trim());
        DatabaseManager dbManager = new DatabaseManager();
        DataTable dt = dbManager.ExecuteQuery(query, param1, param2);
        var objectArray = dt.AsEnumerable()
            .Select(row => new
            {
                Id = row["AirlineID"],
                Name = row["AirlineName"],
            })
           .ToArray();
        return objectArray;
    }
    
    

  2. Your public function is already "automatic" typed as "MyData"

    And yes, the built in serializer always did include the object type, and it always returns the data in the .d part of the object returned.

    Also, your .ajax call is passing data, and that means the function signature should match (you are passing "term").

    So, say this method:

        [WebMethod]
        public static MyData GetDataList(string term)
        {
            int id = 123;
            string value = "My Name " + "(" + term + ")";
    
            return new MyData { Id = id, Value = value };
        }
    

    So, on the client side, then this:

      <input id="Button1" type="button" value="test"
          onclick="testm();return false";
          />
      <script>
    
          function testm() {
    
              var MyTerm = "abc";
              $.ajax({
                  type: 'POST',
                  url: 'AjaxTest41.aspx/GetDataList',
                  data: '{ "term": "' + MyTerm + '" }',
                  contentType: 'application/json; charset=utf-8',
                  dataType: 'json',
                  success: function (data) {
    
                      console.log(data)
                      console.log(data.d.Id)
                      console.log(data.d.Value)
                  },
                  error: function () {
                      console.log('Error fetching items.');
                  }
              });
          }
    
      </script>
    

    result:

    enter image description here

    Note close, we have to prefix the return values with ".d".

    .net been this way for 20 years, and it as a security measure always returns the payload in ".d".

    And yes, the object type is always returned, and again in 99% of cases, we don’t care.

    However, there are several approaches if you want to control what is returned. You can set the web method function as a string and then serialize the object server side, and then client side serialize again. (I don’t particular like doing this, since you doing a double serialize).

    If you really don’t want that extra information, and don’t want the object type included? And you don’t want the .d payload?

    Then simply serialize the object yourself, and do NOT strong type the web method. In fact, mark the method as void, and return whatever you want.

    Hence, say this:

              var MyTerm = "abc";
              $.ajax({
                  type: 'POST',
                  url: 'AjaxTest41.aspx/GetDataList2',
                  data: '{ "term": "' + MyTerm + '" }',
                  contentType: 'application/json; charset=utf-8',
                  dataType: 'json',
                  success: function (data) {
    
                      console.log(data)
                      console.log("Id = " + data.Id)
                      console.log("Value = " + data.Value)
                  },
                  error: function () {
                      console.log('Error fetching items.');
                  }
              });
    

    And server side, we do this:

        [WebMethod]
        public static void  GetDataList2(string term)
        {
            int id = 123;
            string value = "My Name " + "(" + term + ")";
    
            MyData MyResult = new MyData();
            MyResult.Id = id;
            MyResult.Value = value;
    
            JavaScriptSerializer myser = new JavaScriptSerializer();
            HttpContext.Current.Response.Write(myser.Serialize(MyResult));
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.End();
        }
    

    And now client side, we have this:

          function testm() {
    
              var MyTerm = "abc";
              $.ajax({
                  type: 'POST',
                  url: 'AjaxTest41.aspx/GetDataList2',
                  data: JSON.stringify({term : MyTerm}),
                  contentType: 'application/json; charset=utf-8',
                  dataType: 'json',
                  success: function (data) {
    
                      console.log(data)
                      console.log("Id = " + data.Id)
                      console.log("Value = " + data.Value)
                  },
                  error: function () {
                      console.log('Error fetching items.');
                  }
              });
          }
    

    Output:

    enter image description here

    Note that I introduced JSON.stringify, since I don’t like the messy concatenation, and in above, stringify can be used in all of the above examples.

    So, we might have say:

      var sFirstName = "Albert"
      var sLastName = "Kallal"
    

    Then data becomes this:

                  data: JSON.stringify({FirstName: sFirstName, LastName : sLastName}),
    

    And the server-side signature has to match, and thus this:

        [WebMethod]
        public static Whatever GetDataList(string FirstName, string LastName)
        {
    

    Note that prior to .net 4.7.2, it is recommended that you use Newton Soft’s serializer.

    For current 4.8, then you can in most cases use the built in serializer.

    Hence:

    using System.Web.Script.Serialization;
    

    So, you can mark the web method as void, and return whatever you want, and above will remove the ".d", and will remove the passing of the object type.

    However, in most cases, and even using autocomplete from jQuery.UI, then in client-side code, you can just include the .d for your client-side code, and autocomplete can and will work just fine.

    Edit: AutoComplete example

    As I pointed out, the fact of the object type, and that of the return value being inside of ".d"?

    It really does not matter.

    Hence say this markup:

      <h3>Enter Hotel Name</h3>
      <asp:TextBox ID="txtHotel" runat="server" ClientIDMode="Static">
      </asp:TextBox>
    
      <script>
              $(document).ready(function () {
                  $("#txtHotel").autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: "AjaxTest41.aspx/HotelSearch",
                        data: JSON.stringify({ HotelName: request.term }),
                        dataType: "json",
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        dataFilter: function (data) { return data; },
                        success: function (data) {
                            response($.map(data.d, function (item) {
                                return {
                                    value: item
                                }
                            }))
                        }
                    });
                }
            });
        });
      </script>
    

    And the web method behind is this:

        [WebMethod]
        public static List<string> HotelSearch(string HotelName)
        {
            List<string> MyHotelList = new List<string>();
            string strSQL =
                @"SELECT HotelName FROM tblHotels
                WHERE HotelName LIKE @h + '%'
                ORDER BY HotelName";
    
            using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
            {
                using (SqlCommand cmd = new SqlCommand(strSQL,conn))
                {
                    cmd.Parameters.Add("@h", SqlDbType.NVarChar).Value = HotelName;
                    conn.Open();
                    DataTable dtHotels = new DataTable();
                    dtHotels.Load(cmd.ExecuteReader());
                    foreach (DataRow dr in dtHotels.Rows)
                        MyHotelList.Add(dr["HotelName"].ToString());
                }
            }
    
            return MyHotelList;
        }
    

    And the result is this:

    enter image description here

    So, the fact of having to use ".d", and the fact that the object type was included did not matter. Now, I suppose one could perhaps use my above example in which we serialize the List object, and send that to jQuery autocomplete, but it not really much of an issue either way.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search