0

I asked a question to fill in the model data on the client, into arrays.

Add items to JSON objects

Now my problem is how to post it to the controller. I have tried this:

 public ActionResult ItemRequest (Model1 model)
 {
    ////
 }

but it never gets there.

I'm trying with an AJAX request to send it:

 function sendRequest() {
    jsonData.items = itemArray;
    $.ajax({
       url: '@Url.Action("ItemRequest")',
       type: 'POST',
       data: JSON.stringify(jsonData),
       ///// and so on
  }

But the action result is never invoked. I can drop the 'JSON.stringify' and it makes no difference. Any ideas on how to post this object to the controller?

If I make a psuedo model in JS it works fine, but I don't want to have to make this model, I'd rather use the model passed to the page.

  function itemModel () {
     var self = this;
     this.itemNumber = $("#itemNumberId").val();
     /// etc.
     self.items = [];
  }

  function itemsModel () {
    var self = this;
    this.itemNumber = $("#itemNumberId").val();
     /// etc
  }

then

  var itemCount = 0;     
  function addItem() {
    var newItem = new itemModel();
    newItem.items[itemCount] = newItem;
    /// etc
  }

This works fine.

I send the array itemModel the same way with a JSON.stringify directly into the controller method

 public ActionResult ItemRequest(ItemModel model)
Community
  • 1
  • 1
Dean.DePue
  • 1,013
  • 1
  • 21
  • 45
  • For starters you are attempting to pass an Array object into a single object on the server. Also, you are assigning `itemArray` to `jsonData.items` but are stringify'ing and passing `jsonData` – CSharper Oct 14 '14 at 19:55
  • @CSharper - OK, I get it, then what should I pass and how? – Dean.DePue Oct 14 '14 at 20:58

1 Answers1

0

We are using this to send Data to API controller Methods on our internal test sides: It's probably not the prettiest solution, but it can be used on any page.

What data should be sent:

$("#btnSend").click(function () {call("controller/method", {ParamName: $("#field").val()}); });

To send the data to a controller:

$(document).ready(function () {
    var call = function (method, requestData, resultHandler) {
        var url = method.substring(0, 1) == "/api/" + method;

        $.ajax({
            url: url,
            dataType: 'json',
            data: JSON.stringify(requestData),
            type: 'POST',
            contentType: 'application/json',
            success: function (data) {
                var isSuccess = data.Status == "success";
                $("#jsonResponse").val(FormatJSON(data));

                if (isSuccess && jQuery.isFunction(resultHandler)) {
                    resultHandler(data);
                }
            }
        });
    };
Darkglow
  • 683
  • 2
  • 8
  • 18