1

ここに画像の説明を入力してください

ここに画像の説明を入力してください

上記では、動的UIと、日付に応じて関連フィールドのIDを動的に設定する方法を示しました。

したがって、これらのデータをアレイajaxポストとしてMVCコントローラーに送信し、コントローラー内でそれらを選択する必要があります。これは、[保存]ボタンをクリックしたときに発生するはずです。

私のpostメソッドは以下のとおりです(上記の配列の詳細はありません):

 $("#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;
       });

私のコントローラーは以下のとおりです(jquery配列のmaupulationなし):

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

        }

アップデート

UIは、以下のコードを使用して生成されています。

<% 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>
    <% }%>

私の質問:

  1. ajaxを使用して、行データごとに上記の動的2フィールドを送信するにはどうすればよいですか?

  2. コントローラ内でそのアレイを操作する方法は?

4

2 に答える 2

2

取得したいデータを表すビューモデルをサーバー上で定義することから始めることができます。

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; }
}

次に、コントローラーアクションにこのビューモデルを引数として使用させます。

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

次のステップは、ビューを少し修正することです。これは、現在、HTMLヘルパーを使用して入力フィールドに間違ったIDと名前を定義する代わりに、入力フィールドをハードコーディングしているように見えるためです(HTMLではidname属性は数字で始めることはできません)。

したがって、テーブルを生成する方法は次のとおりです。

<% 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>
<% } %>

.submitそして最後に、フォームのハンドラーにサブスクライブして値をサーバーに送信するjavascriptファイルを作成できます。

$(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;
});

この例では、非推奨であり、今後は使用しない.on()方法の代わりに、この方法をどのように使用したかに注目してください。.live()

于 2013-03-16T17:32:23.960 に答える
1

この答えはあなたの一番の質問です。

を使用してすべてのフォームデータを送信できますform.serialize()。例えば

$.ajax({
    ...
    data: $('#yourformId').serialize(),
    ...
});
于 2013-03-16T09:00:05.450 に答える