views:

374

answers:

1

Using jquery to post values back to an asp.net webform. I have some code that works great for sticking posted Form values into my object, basically it converts the form values into the correct type for each property in my class.

if (Request.Form.HasKeys())
{
    foreach (var key in Request.Form.AllKeys)
    {
        PropertyInfo itemProperty = _CmsItem.GetType().GetProperty(key, BindingFlags.Public | BindingFlags.Instance);

        var value = Request.Form[key];
        if (itemProperty != null)
        {
            itemProperty.SetValue(_CmsItem, Convert.ChangeType(value, itemProperty.PropertyType), null);
        }
    }
    // Doing some processing with my object
}

Now I have run into a quandary on how to handle a string like MyKeys = 123,13332,232323 and get that into an array or list in my object. What would be the best way to handle this situation?

Clarification: I have built the page to handle regular form posts as well as $ajax callback posts based on a requestmode flag so the page / or parts of the page can be re-used based on different circumstances.

+1  A: 

The easiest way to parse a list in the format you gave above would be to just use string.Split(...).

The ideal way to handle lists and objects from JavaScript to the server is to use JSON. This is standardized and intuitive to most developers. It has the added bonus of being easy to parse in ASP.NET with a generic API.

In the example below, I assume that the value of the list is literally "[123,13332,232323]" (without quotes). This will convert the value into a string array. It uses the JavaScriptSerializer class for JSON parsing. This class requires your project to have a reference to the System.Web.Extensions DLL, which is part of the .NET 3.5 framework but not always included by default in projects.

using System.Web.Script.Serialization;

[...]

if (Request.Form.HasKeys())
{
    JavaScriptSerializer serializer = new JavaScriptSerializer();
    foreach (var key in Request.Form.AllKeys)
    {
        var value = Request.Form[key];

        var list = serializer.Deserialize<string[]>(value);

    }
}

I also just tested this with other types (aside from just a string[]) and the Deserialize<T>() method also will convert objects into int[], List<string>, and List<int>, so it's farily dynamic, and doesn't require a lot of effort to parse.

Dan Herbert
At this point in the project, it needs to be done tomorrow, I will have to go with the string.Split() for now. I will have to visit the Json later.
Breadtruck