0

I have an .aspx page that we are loading UserControls into dynamically at runtime. Each user control has some sort of textbox or combo or some other control. This all works fine. when we go to read the values out of the controls when the user presses search, we cannot do this directlly from C# code behind because the page does not know they are there. my solution is to read the values with JQuery and make an ajax call where I can set the values in a session variable for use when the user gets to the next page. I am having trouble with the JSon specifically. I keep getting the error:

{"Message":"Cannot convert object of type \u0027System.String\u0027 to type \u0027System.Collections.Generic.IDictionary`2[System.String,System.Object]\u0027","StackTrace":" 

I find all the controls using .each and get the values for the JSon call:

        function SaveFields() {
        var data = [];

        //get Search field criteria
        $('[id^=Search_ucField_]').each(function (index, value) {
            var field = $(this);
            var id = $(this).attr('id').split("_")[2];
            var fieldValue = $(this).val();

            if (field.is('input')) {
                var item = {};
                item['FieldID'] = id;
                item['Criteria'] = fieldValue;
                item['IsActive'] = 1;
                item['FieldCategoryID'] = '1';
                item['ControlPath'] = '~/Controls/Search/TextBox.aspx';
                item['CategoryID'] = 1;         
                data.push(item);
            }
        });

        $.ajax({
            url: '/Ajax/Ajax.aspx/DoSearch',
            type: 'POST',
            data: JSON.stringify(data),
            datatype: 'json',
            contentType: 'application/json',
            success: function (msg) {
                console.log(msg);
            },
            error: function (xhr, textStatus, errorThrown) {
                alert('Error!  Status = ' + xhr.status);
            }
        });
}

Here is the object I am trying to deserialize into:

[DataContract]
public class SearchFields
{
    [DataMember]
    public List<SearchField> Field { get; set; }
}

[DataContract]
public class SearchField
{
    [DataMember]
    public string FieldID { get; set; }
    [DataMember]
    public bool IsActive { get; set; }
    [DataMember]
    public string Criteria { get; set; }
    [DataMember]
    public int FieldCategoryID { get; set; }
    [DataMember]
    public string ControlPath { get; set; }
}

Here is the WebMethod

        [WebMethod]
    public static string DoSearch(string Fields) 
    {

        var sf = new SearchFields();

        sf = JsonConvert.DeserializeObject<SearchFields>(Fields);

        //save into session variable
        SVars.NewUISearch.LastSearchFields = sf;

        string x;
        x = "until this works, this is a static response";
        return x;

    }

finally, here is a sample of the JSon that is being sent:

[{"FieldID":"52","getCriteria":"Bobs your uncle","IsActive":1,"FieldCategoryID":"1","ControlPath":"~/Controls/Search/TextBox.aspx"}]

Where am I going wrong here? Thanks in advance!

  • Instead of DoSearch accepting the JSON string, you can pass the entire strongly typed model through Ajax. Try adding this to the Ajax data param: `$(#YourForm).serialize()` and DoSearch have the ViewModel as a param – CSharper Sep 17 '14 at 19:34
  • @Scott Loveland If you do that, which you should, you will need to match the field names and types to the strong type. Then Asp.Net model binding will do all the work for you. To be clear, your method signature would change to `DoSearch( SearchField field)` – Steve Mallory Sep 17 '14 at 19:38
  • Might help: http://stackoverflow.com/questions/736058/passing-parameter-to-webmethod-with-jquery-ajax – Rick S Sep 17 '14 at 19:43
  • OK, I understand changing the signature in the method, that makes sense, but I dont understand quite where I would add $(#myform).serialize() – Scott Loveland Sep 17 '14 at 19:57
  • I finally got this working after I removed the [] from the json and changed the signature in my method to accept the object. Thanks for your help guys! – Scott Loveland Sep 18 '14 at 00:14

1 Answers1

0

I couldn't get $('form').serialize() to work so this is what I did. Make sure the properties you define in model represent the properties in your model and are strongly typed.

 var model = {        
        MyString: $("#MyString").val(), 
        MyNumber: $("#MyNumber").val(),
        IsCheck: $("CHK").val()
    };     

    $.ajax({
        type: "POST",
        url: "/Testing/Index",
        contentType: "application/json",
        data: JSON.stringify(model),
        dataType: "json",
        success: function (data) {
            // Good stuff
        },
        error: function (data) {
            // Bad stuff
        }
    })
CSharper
  • 5,420
  • 6
  • 28
  • 54