Your Privacy Matters: We use our own and third-party cookies to improve your experience on our website. By continuing to use the website we understand that you accept their use. Cookie Policy
20
POST AXJX calling flinging in Infragistics.Web.Mvc
posted

Model:

public class Product
{
public int ProductID { get; set; }
public string Name { get; set; }
public string ProductNumber { get; set; }

public List<ProductLocations> Locations { get; set; }
}

public class ProductLocations
{
public string Address { get; set; }
}

Controller 

[GridDataSourceAction]
[HttpPost]
public ActionResult PostDataMethod3(Product Param1, string Param2, string Param3)
{
try
{
List<Product> products = new List<Product>();

products.Add(new Product { ProductID = 1, Name = "Product 1", ProductNumber = "12345" });
products.Add(new Product { ProductID = 2, Name = "Product 2", ProductNumber = "12346" });
products.Add(new Product { ProductID = 3, Name = "Product 3", ProductNumber = "12347" });
products.Add(new Product { ProductID = 4, Name = "Product 4", ProductNumber = "12348" });
products.Add(new Product { ProductID = 5, Name = "Product 5", ProductNumber = "12349" });

return View(products.AsQueryable());
}
catch (Exception ex)
{
string error = ex.Message;
return null;
}

}

AJAX call

var appJson = {
"Param1": { "ProductID": 1, "Name": "test product", "ProductNumber": "P123", "Locations": [{ "Address": "Address1" }, { "Address": "Address2" }]}, "Param2": "Param2", "Param3": "Param3" };

$('#postData3').click(function (e) {
e.preventDefault();

$.ajax({
url: '@(Url.Action("PostDataMethod3"))',
type: 'POST',
traditional: true,
contentType: "application/json",
dataType: "json",
data: JSON.stringify(appJson),
success: function (response) {
alert('Succcess');
$('#grid').igGrid({ dataSource: response }).igGrid("dataBind");
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Failure - ' + xhr.responseText);
$('#grid').igGrid({ dataSource: null }).igGrid("dataBind");
}
});
});

Eroor:

2022infragisticerror.igGridQueryStringToJson.zip

  • 60
    Offline posted

    Hello Anitha,

     

    Thank you for the provided sample! 

    I’ve been looking into your question and after an investigation what I could say is that the initial error is thrown because the “appJson” variable was not being parsed properly. It can be passed to the “data” property without being stringified.  Another issue I have found is that the “PostDataMethod3” never receives its parameters even if the grid loads, so changing the code in the following way provides the desired results: 

     

                var appJson = {

                Param1: { "ProductID": 1, "Name": "test product", "ProductNumber": "P123", "Locations": [{ "Address": "Address1" }] },

                Param2: { "ProductID": 2, "Name": "test product", "ProductNumber": "P123", "Locations": [{ "Address": "Address1" }] },

                Param3: { "ProductID": 3, "Name": "test product", "ProductNumber": "P123", "Locations": [{ "Address": "Address1" }] }

            }

     

    $.ajax({

                    url: '@(Url.Action("PostDataMethod3"))',

                    type: 'POST',

                    data: appJson,

                    success: function (response) {

                        alert("Success");

                        $('#grid').igGrid({ dataSource: response }).igGrid("dataBind");

                    },

                    error: function (xhr, ajaxOptions, thrownError) {

                        alert('Failure - ' + xhr.responseText);

                        $('#grid').igGrid({ dataSource: null }).igGrid("dataBind");

                    }

                });

     

    Attached could be found my sample for your reference. Please test it on your side and let me know how it behaves.

    Regards,
    Aleksandar Atanasov,

    Infragistics.

    Index.zip

  • 15
    Offline posted in reply to Axl Atanasov

    No working  it's same issue as earlier 

    Note: which is working on our old  Infragistics.Web.Mvc 2017.

    Not working  Infragistics.Web.Mvc 2022 we received recently for upgrade.

    attached dll for your reference.

    dll.zip

    Controller:

    ============================

    [GridDataSourceAction]
    [HttpPost]
    public ActionResult PostDataMethod3(Product Param1, Product Param2, Product Param3)
    {
    try
    {
    List<Product> products = new List<Product>();

    products.Add(new Product { ProductID = 1, Name = "Product 1", ProductNumber = "12345" });
    products.Add(new Product { ProductID = 2, Name = "Product 2", ProductNumber = "12346" });
    products.Add(new Product { ProductID = 3, Name = "Product 3", ProductNumber = "12347" });
    products.Add(new Product { ProductID = 4, Name = "Product 4", ProductNumber = "12348" });
    products.Add(new Product { ProductID = 5, Name = "Product 5", ProductNumber = "12349" });

    return View(products.AsQueryable());
    }
    catch (Exception ex)
    {
    string error = ex.Message;
    return null;
    }

    }

    Ajax

    =====================

    //json2
    var appJson2 = {
    "Param1": { "ProductID": 1, "Name": "test product", "ProductNumber": "P123", "Locations": [{ "Address": "Address1" }] },
    Param2: { "ProductID": 2, "Name": "test product", "ProductNumber": "P123", "Locations": [{ "Address": "Address1" }] },
    Param3: { "ProductID": 3, "Name": "test product", "ProductNumber": "P123", "Locations": [{ "Address": "Address1" }] }
    }


    $('#postData3').click(function (e) {
    e.preventDefault();

    $.ajax({
    url: '@(Url.Action("PostDataMethod3"))',
    type: 'POST',
    data: appJson2,
    success: function (response) {
    alert("Success");
    $('#grid').igGrid({ dataSource: response }).igGrid("dataBind");
    },
    error: function (xhr, ajaxOptions, thrownError) {
    alert('Failure - ' + xhr.responseText);
    $('#grid').igGrid({ dataSource: null }).igGrid("dataBind");
    }
    });
    });

    viewmodel

    ================================

    public class Product
    {
    public int ProductID { get; set; }
    public string Name { get; set; }
    public string ProductNumber { get; set; }

    public List<ProductLocations> Locations { get; set; }
    }

    public class ProductLocations
    {
    public string Address { get; set; }
    }

  • 15
    Offline posted in reply to Anitha Maddala

    It's clear issue on Assembly: Infragistics.Web.Mvc, Version=5.22.2.7

    Class: GridDataSourceActionAttribute

    Method: OnActionExecuted

    Line: Dictionary<string, string> source = JsonConvert.DeserializeObject<Dictionary<string, string>>(new StreamReader(inputStream).ReadToEnd());

    I have reproduced this issue on my local. I just copied  Infragistics.Web.Mvc, Version=5.22.2.7 GridDataSourceActionAttribute code on my own ActionAttribute

    I am attaching source code of  Infragistics.Web.Mvc, Version=5.22.2.7 GridDataSourceActionAttribute.

    GridDataSourceActionAttribute.txt
    // Decompiled with JetBrains decompiler
    // Type: Infragistics.Web.Mvc.GridDataSourceActionAttribute
    // Assembly: Infragistics.Web.Mvc, Version=5.22.2.7, Culture=neutral, PublicKeyToken=7dd5c3163f2cd0cb
    // MVID: B14562A4-A11D-4AD5-95C6-5495B1038B24
    // Assembly location: C:\Users\amaddala\source\repos\dll\2022\Infragistics.Web.Mvc.dll
    // XML documentation location: C:\Users\amaddala\source\repos\dll\2022\Infragistics.Web.Mvc.xml
    
    using Newtonsoft.Json;
    using System;
    using System.Collections.Generic;
    using System.Collections.Specialized;
    using System.Data;
    using System.IO;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    
    namespace Infragistics.Web.Mvc
    {
      /// <summary>
      /// this is an attribute class which extends the mvc FilterAttribute. It should be put on top of the controller method
      /// that should return JSON (even though in the user code it will return Action Result).
      /// The idea of this filter is to transform the ActionResult into a JsonResult instance, taking into account all Request params
      /// such as paging, sorting, and filtering. Since MVC doesn't have ViewState, we will need to infer all the features from the request itself, that's
      /// the only information we have regarding any previous state.
      /// </summary>
      public class GridDataSourceActionAttribute : FilterAttribute, IActionFilter
      {
        /// <summary>Instantiate grid model</summary>
        /// <returns></returns>
        internal virtual GridModel InstantiateGridModel() => (GridModel) new InternalGridModel();
    
        /// <summary>
        /// infers enabled grid features based on request parameters
        /// </summary>
        /// <param name="queryString"></param>
        /// <returns></returns>
        internal virtual List<GridFeature> GetFeaturesFromQueryString(NameValueCollection queryString) => GridDataSourceActionAttribute.InferFeatures(queryString);
    
        /// <summary>Sets the model properties from query string.</summary>
        /// <param name="model">The model.</param>
        /// <param name="queryString">The query string.</param>
        internal virtual void SetModelPropertiesFromQueryString(
          GridModel model,
          NameValueCollection queryString)
        {
        }
    
        /// <summary>
        /// intercepts the controller call, and transforms the action result into a json result.
        /// </summary>
        /// <param name="filterContext"></param>
        public void OnActionExecuted(ActionExecutedContext filterContext)
        {
          if (!AjaxRequestExtensions.IsAjaxRequest(((ControllerContext) filterContext).HttpContext.Request))
            return;
          GridModel model = this.InstantiateGridModel();
          model.DataSource = !typeof (DataTable).IsAssignableFrom(((ControllerContext) filterContext).Controller.ViewData.Model.GetType()) ? (!typeof (DataSet).IsAssignableFrom(((ControllerContext) filterContext).Controller.ViewData.Model.GetType()) ? (object) (((ControllerContext) filterContext).Controller.ViewData.Model as IQueryable) : (object) (((ControllerContext) filterContext).Controller.ViewData.Model as DataSet)) : (object) (((ControllerContext) filterContext).Controller.ViewData.Model as DataTable);
          NameValueCollection nameValueCollection = ((ControllerContext) filterContext).HttpContext.Request.QueryString;
          if (HttpContext.Current != null && HttpContext.Current.Request.HttpMethod == "POST")
          {
            Stream inputStream = ((ControllerContext) filterContext).HttpContext.Request.InputStream;
            inputStream.Seek(0L, SeekOrigin.Begin);
            Dictionary<string, string> source = JsonConvert.DeserializeObject<Dictionary<string, string>>(new StreamReader(inputStream).ReadToEnd());
            if (source != null)
              nameValueCollection = source.Aggregate<KeyValuePair<string, string>, NameValueCollection>(new NameValueCollection(nameValueCollection), (Func<NameValueCollection, KeyValuePair<string, string>, NameValueCollection>) ((seed, current) =>
              {
                seed.Add(current.Key, current.Value);
                return seed;
              }));
          }
          this.SetModelPropertiesFromQueryString(model, nameValueCollection);
          if (((IEnumerable<string>) nameValueCollection.AllKeys).Contains<string>("dbdepth"))
            model.AutoGenerateLayouts = new bool?(true);
          if (nameValueCollection["layout"] == null)
            model.Features = this.GetFeaturesFromQueryString(nameValueCollection);
          if (nameValueCollection["pk"] != null)
            model.PrimaryKey = nameValueCollection["pk"];
          if (((ControllerContext) filterContext).Controller.ViewData["GenerateCompactJSONResponse"] != null && !(bool) ((ControllerContext) filterContext).Controller.ViewData["GenerateCompactJSONResponse"])
            model.GenerateCompactJSONResponse = new bool?(false);
          filterContext.Result = (ActionResult) model.GetData();
        }
    
        /// <summary>implementation of the ActionExecuting event</summary>
        /// <param name="filterContext"></param>
        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
        }
    
        /// <summary>
        /// Check whether feature(specified by feature name) exists in list of grid features. If not - add it in the list.
        /// </summary>
        /// <param name="listFeatures">The list features.</param>
        /// <param name="featureName">Name of the feature.</param>
        /// <param name="gridFeatureFactory">The grid feature factory used to instantiate grid feature by feature name.</param>
        private static void CheckExistAndAddGridFeature(
          List<GridFeature> listFeatures,
          string featureName,
          BaseGridFeatureFactory gridFeatureFactory)
        {
          if (string.IsNullOrEmpty(featureName))
            return;
          featureName = featureName.ToLower();
          if (listFeatures.Where<GridFeature>((System.Func<GridFeature, bool>) (f => f.Name.ToLower() == featureName)).Count<GridFeature>() > 0)
            return;
          GridFeature gridFeatureInstance = gridFeatureFactory.CreateGridFeatureInstance(featureName);
          if (gridFeatureInstance == null)
            return;
          listFeatures.Add(gridFeatureInstance);
        }
    
        /// <summary>
        /// infers enabled grid features based on request params and values. GridFeatures are instantiated from the passed parameter gridFeatureFactory.
        /// </summary>
        /// <param name="queryString"></param>
        /// <param name="gridFeatureFactory">Optioonal parameter. If not passed it is used instance of GridFeatureFactory</param>
        /// <returns></returns>
        public static List<GridFeature> InferFeatures(
          NameValueCollection queryString,
          BaseGridFeatureFactory gridFeatureFactory = null)
        {
          List<GridFeature> listFeatures = new List<GridFeature>();
          if (gridFeatureFactory == null)
            gridFeatureFactory = (BaseGridFeatureFactory) new GridFeatureFactory();
          foreach (string key in queryString.Keys)
          {
            if (key != null && key.StartsWith("sort"))
            {
              GridDataSourceActionAttribute.CheckExistAndAddGridFeature(listFeatures, "sorting", gridFeatureFactory);
              GridDataSourceActionAttribute.CheckExistAndAddGridFeature(listFeatures, "groupby", gridFeatureFactory);
            }
            else if (key != null && key.StartsWith("filter"))
              GridDataSourceActionAttribute.CheckExistAndAddGridFeature(listFeatures, "filtering", gridFeatureFactory);
            else if (key != null && key.StartsWith("Summaries"))
              GridDataSourceActionAttribute.CheckExistAndAddGridFeature(listFeatures, "summaries", gridFeatureFactory);
          }
          if (queryString["pageSize"] != null && queryString["page"] != null)
            GridDataSourceActionAttribute.CheckExistAndAddGridFeature(listFeatures, "paging", gridFeatureFactory);
          return listFeatures;
        }
      }
    }
    

    Axl Atanasov Do you have solution for this?

  • 15
    Offline posted in reply to Anitha Maddala

    Axl Atanasov any update on this.