0

I would like to pass dictionary from AJAX to the controller so where I go trough the all input element I would like to create dictionary<element.name as TKey, element.value as TValue>

How its that possible?

controller

[HttpPost]
public ActionResult SearchResult(int reportId, Dictionary<string, object> elementValue)

js

$("#btnSearch").click(function() {
  var reportId = $(this).data("id");

  var elementValues = {};
  $("#pnlFilter :input").each(function() {
    if ($(this).attr("type") === "checkbox") {
      elementValues = {
        "key": this.name,
        "value": $(this).is(":checked")
      };
      //elementValues.push(this.name + "-" + $(this).is(":checked"));
    } else {
      elementValues = {
        "key": this.name,
        "value": this.value
      };
      //elementValues.push(this.name + "-" + this.value);
    }
  });

  alert(elementValues);

  $.ajaxSetup({
    cache: false
  });
  $.ajax({
    type: "POST",
    url: "/Report/SearchResult",
    contentType: "application/json; charset=utf-8",
    data: JSON.stringify({
      reportId,
      elementValues
    }),
    dataType: "json",
    success: function() {
      var url = "/Report/EditFilters?reportId=" + reportId;
      $("#pageContent").load(url);
    }
  });
});
Mosh Feu
  • 28,354
  • 16
  • 88
  • 135
Baba.Kata
  • 23
  • 1
  • 7
  • Is not a duplicate, i cant do int on that way. I always got this https://imgur.com/a/aI1iP – Baba.Kata Jan 23 '18 at 12:36
  • Buddy check this [link] (https://alexkuznetsov.wordpress.com/2013/05/08/asp-net-mvc-pass-dictionary-data-from-view-to-controller/) , i think problem with creating "elementValues" in your script. – Ray Jan 23 '18 at 13:08
  • A `Dictionary` is a collection - your just sending `elementValues` which is an object, not an array –  Jan 24 '18 at 22:53
  • And it also needs to be `data: JSON.stringify({ reportId: reportId, elementValue: elementValues }),` –  Jan 24 '18 at 23:01

0 Answers0