locked
getting array object values from jQuery in code behind on button click event..... RRS feed

  • Question

  • User-153404742 posted

    Hi,

    I'm trying to post values back to the server on button click event, which runs jQuery function.  I"m trying to get values in code behind when button is clicked.  Following is the code:

    <asp:Button ID="btnSave" runat="server" class="save-mapping-btn" OnClick="btnSave_Click" Text="Save Mapping" />

    $('.save-mapping-btn').on('click', function () { var tData = []; $('.my-item').each(function (i, el) { var attr = $(el).attr('data-eid'); if (typeof attr !== typeof undefined && attr !== false) { var eid= $(el).data().eid; var pid= $(el).data().id; tData.push({ p_id: pid, e_id: eid, }); } }); if (tData.length > 0) { //POST mapping data to server; //console.info(tData); } });

    Tuesday, May 22, 2018 6:46 PM

All replies

  • User-474980206 posted

    there a lot of ways.

    1) use ajax to do the post. use FormData, and add the collection

    2) use a hidden field and serialize the array into a know format (csv, json, piped, xml) and include in the form post

    3) add a form field for each item to the form so they are included in the post.

     

     

    Tuesday, May 22, 2018 10:22 PM
  • User-153404742 posted

    I've tried returning the array by splitting the values delimited by "|" but in code behind hiddenfield value just says {"object","object}....so I tried to stringify the value in JSON and it returns the following value in hiddenfield

    "[{\"p_id\":\"Test 2\",\"e_id\":1},{\"p_id\":\"Test 3\",\"e_id\":2}]"

    It gives error saying cannot deserialize array....I'm doing the following:

    public class Mapping
    {
    [JsonProperty("p_id")]
    public string pID { get; set; }
    [JsonProperty("e_id")]
    public string eID { get; set; }
    }
    JavaScriptSerializer ser = new JavaScriptSerializer(); Mapping es = ser.Deserialize(hiddenfieldID.Value);
    How can I deserialize the "[{\"p_id\":\"Test 2\",\"e_id\":1},{\"p_id\":\"Test 3\",\"e_id\":2}]" into something where I can get values like es.pID and es.eID? I've tried deserializing as a list object and doesn't work either.
    Wednesday, May 23, 2018 5:25 PM
  • User-474980206 posted

    you need a .net object

    public class MyObject {
       public string p_id {get; set;}
       public int e_id {get; set;}
    }
    
    var json = "[{\"p_id\":\"Test 2\",\"e_id\":1},{\"p_id\":\"Test 3\",\"e_id\":2}]";
    var list = JsonConvert.DeserializeObject<List<MyObject>>(json;)
    


    Thursday, May 24, 2018 1:52 AM