Sampath
Sampath

Reputation: 65860

Send Ajax Array to Controller

enter image description here

enter image description here

Above I have showed the my dynamic UI and the way I set the ids dynamically for the relevant fields according to the date.

So I need to send theses data into MVC controller as a array ajax post and then pick those things inside the controller.This should be happened when I click Save button

My post method is as below (without above array details):

 $("#clocked-details").find("#btnSave").die('click').live('click', function () {

       var yearValue = $("#year").val();
       var monthValue = $("#month").val();

       $.ajax({
          url: "/Employees/UpdateEmployeeClockedHoursByProvider",
          type: 'POST',
          cache: false,
          data: { employeeId: employeeId, year: yearValue, month: monthValue },
          success: function (result) {

          },
          error: function (xhr, ajaxOptions, thrownError) {
                 alert(xhr.status);
                 alert(thrownError);
               }
           });
          return false;
       });

My controller is as below (without jquery array maupulation) :

[HttpPost]
public void UpdateEmployeeClockedHoursByProvider(Guid employeeId, int year, int month)
        {

        }

Update

UI has been generated by using below mentioned code :

<% foreach (var ec in Model)
       {%>
    <tr>
        <td>
            <%: ec.ClockedDate.ToString("yyyy-MM-dd") %>
        </td>
        <td>
            <input type="number" id="<%: ec.ClockedDate.ToString("yyyy-MM-dd") %>-hours" name="<%: ec.ClockedDate.ToString("yyyy-MM-dd") %>-hours"
                class="total-hours" placeholder="Hours" value="<%: ec.TotalHours %>" />
        </td>
        <td>
            <input type="number" id="<%: ec.ClockedDate.ToString("yyyy-MM-dd") %>-minutes" name="<%: ec.ClockedDate.ToString("yyyy-MM-dd") %>-minutes"
                class="total-minutes" placeholder="Minutes" value="<%: ec.TotalMinutes %>" />
        </td>
    </tr>
    <% }%>

My Questions :

  1. How to send above dynamic 2 fields per row data by using ajax ?

  2. How to manipulate that array inside the controller ?

Upvotes: 1

Views: 2380

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

You could start by defining a view model on the server that will represent the data you would like to retrieve:

public class MyViewModel
{
    public Guid EmployeeId { get; set; }
    public int Year { get; set; }
    public int Month { get; set; }

    public ItemViewModel[] Items { get; set; }
}

public class ItemViewModel
{
    public int TotalHours { get; set; }
    public int TotalMinutes { get; set; }
}

and then have your controller action take this view model as argument:

[HttpPost]
public ActionResult UpdateEmployeeClockedHoursByProvider(MyViewModel model)
{
    ...
}

The next step is to fix your view a little bit because right now you seem to be hardcoding input fields instead of using html helpers and defining wrong ids and names for your input fields (in HTML the id and name attribute cannot start with a number).

So here's how you could generate the table:

<% using (Html.BeginForm("UpdateEmployeeClockedHoursByProvider", null, FormMethod.Post, new { id = "myForm" })) { %>
    <table>
        <thead>
            <tr>
                <th>Clocked Date</th>
                <th>Total Hours</th>
                <th>Total Minutes</th>
            <tr>
        </thead>
        <tbody>
            <% for (var i = 0; i < Model.Count; i++) { %>
            <tr>
                <td>
                    <%= Html.DisplayFor(x => x[i].ClockedDate) %>
                </td>
                <td>
                    <%= Html.TextBoxFor(
                        x => x[i].TotalHours, 
                        new { 
                            type = "number", 
                            placeholder = "Hours", 
                            @class = "total-hours" 
                        }
                    ) %>
                </td>
                <td>
                    <%= Html.TextBoxFor(
                        x => x[i].TotalMinutes, 
                        new { 
                            type = "number", 
                            placeholder = "Minutes", 
                            @class = "total-minutes" 
                        }
                    ) %>
                </td>                    
            </tr>
        <% } %>
        </tbody>
    </table>

    <button type="submit">Save</button>
<% } %>

and finally you could have some javascript file that will subscribe to the .submit handler of the form and send the values to the server:

$(document).on('#myForm', 'submit', function () {
    var items = [];
    $('table tbody tr').each(function() {
        items.push({
            totalHours: $(this).find('td input.total-hours').val(),
            totalMinutes: $(this).find('td input.total-minutes').val()
        });
    });

    var data = {
        employeeId: employeeId, // <!-- It's not very clear from your code where is this supposed to come from
        year: $('#year').val(),
        month: $('#month').val(),
        items: items
    };

    $.ajax({
        url: this.action,
        type: this.method,
        contentType: 'application/json',
        data: JSON.stringify(data),
        success: function (result) {
            // TODO: here you could handle the response from the server
            alert('Your request has been successfully processed.');
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(xhr.status);
            alert(thrownError);
        }
    });

    return false;
});

In this example notice how I used the .on() method instead of .live() which is deprecated and should not be used anymore.

Upvotes: 2

novalagung
novalagung

Reputation: 11502

this answer is for your no.1 querstions.

you can send all form data using form.serialize(). eg

$.ajax({
    ...
    data: $('#yourformId').serialize(),
    ...
});

Upvotes: 1

Related Questions