Ognjen
Ognjen

Reputation: 1195

Beginner problem with posting data table to JsonResult

With this script I get data from JsonResult (GetDevicesTable) and put them to table ( id="OrderDevices")

 <script type="text/javascript">

$(document).ready(function() {

    $("#getDevices a").click(function() {
        var Id = $(this).attr("rel");
        var rowToMove = $(this).closest("tr");
        $.post("/ImportXML/GetDevicesTable", { Id: Id }, function(data) {
        if (data.success) {
            //remove row
            rowToMove.fadeOut(function() { $(this).remove() });
            //add row to other table
            $("#OrderDevices").append("<tr><td>"+ data.DeviceId+ "</td><td>" + data.Id+  "</td><td>" + data.OrderId +  "</td></tr>");                    
            } else {
                alert(data.ErrorMsg);
            }
        }, "json");
    });

});

   <% using (Html.BeginForm()) {%>
   <table id="OrderDevices" class="data-table">
   <tr>

        <th>
            DeviceId
        </th>
        <th>
            Id
        </th>
        <th>
            OrderId
        </th>
    </tr>
   </table>
         <p>
            <input type="submit" value="Submit" />
        </p>
 <% } %>

When click on Submit I need something like this:

    $(document).ready(function() {

    $("#submit").click(function() {
        var Id = $(this).attr("rel");
        var DeviceId = $(this).attr(???);
        var OrderId = $(this).attr(???);
        var rowToMove = $(this).closest("tr");
        $.post("/ImportXML/DevicesActions", { Id: Id, DeviceId:DeviceId, OrderId:OrderId }, function(data) {

        }, "json");
    });
});

I have problem with this script because do not know how post data to this JsonResult:

    public JsonResult DevicesActions(int Id,int DeviceId,int OrderId)
    {
     orderdevice ord = new orderdevice();
            ord.Id = Id;
            ord.OrderId = DeviceId;
            ord.DeviceId = OrderId;

            DBEntities.AddToorderdevice(ord);
            DBEntities.SaveChanges();
    }

Upvotes: 3

Views: 458

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038830

In order to get all the ids, deviceIds and orderIds from the table you will need to modify the action signature so that it can accept arrays:

public ActionResult DevicesActions(int[] ids, int[] deviceIds, int[] orderIds)
{
    ...
}

Now that you have this in place you can send the AJAX query:

var deviceIds = $('#OrderDevices tr td:first-child').map(getValue);
var ids = $('#OrderDevices tr td:nth-child(2)').map(getValue);
var orderIds = $('#OrderDevices tr td:nth-child(3)').map(getValue);
$.post(
    '/ImportXML/DevicesActions', 
    {
        deviceIds: deviceIds,
        ids: ids,
        orderIds: orderIds
    }, 
    function(json) {
        // success
    }
);

and the getValue function used to map:

function getValue() {
    return parseInt($(this).text());
}

Upvotes: 2

Related Questions