Transfer dynamic data to mvc controller using AJAX

How to transfer data dynamicwhen calling AJAXto MVC Controller?

Controller:

public JsonResult ApplyFilters(dynamic filters){
   return null;
}

Call AJAX:

$(':checkbox').click(function (event) {
    var serviceIds = $('input[type="checkbox"]:checked').map(function () {
        return $(this).val();
    }).toArray();

    //alert(serviceIds);

    $.ajax({
        type: 'GET',
        url: '/home/ApplyFilters',
        data: JSON.stringify({
            name: serviceIds
        }),
        contentType: 'application/json',

        success: function (data) {
            alert("succeeded");
        },
        error: function (err, data) {
            alert("Error " + err.responseText);
        }
    });

    //return false;
});

Ideally, it would be what filterswould contain serviceIdsas a property

For example, for example filters.ServiceIds. I have another filter for a range of dates, and it will be added as follows: filters.DateRange.

And the server side receives the filter as an object dynamicinApplyFilters()

+4
source share
1 answer

So far, since I know that the standard ASP MVC middleware cannot do this thing.

, , :

1. , JSON IDictionary<string, object>, . :

public JsonResult ApplyFilters(IDictionary<string, object> filters)
{
   return null;
}

2. JsonValue. :

public JsonResult ApplyFilters([DynamicJson]JsonValue filters)
{
   return null;
}

3. , , . . , :

public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
    if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
    {
        return null;
    }

    controllerContext.HttpContext.Request.InputStream.Position = 0;
    using (var reader = new StreamReader(controllerContext.HttpContext.Request.InputStream))
    {
        var json = reader.ReadToEnd();
        if (string.IsNullOrEmpty(json))
        {
            return null;
        }
        dynamic result = new ExpandoObject();
        var deserializedObject = new JavaScriptSerializer().DeserializeObject(json) as IDictionary<string, object>;
        if (deserializedObject != null)
        {
            foreach (var item in deserializedObject)
            {
                ((IDictionary<string, object>)result).Add(item.Key, item.Value);
            }
        }
        return result;
    }
}

:

+7

All Articles