1

MVC にテーブル レイアウトがあり (以下のコードを参照)、テーブルの各行に送信ボタンがあります。各送信ボタンは、同じコントローラー メソッド 'TableSample' にポストされます。選択した行IDをキャプチャして投稿する方法は?

public class TableSample
{
    public string Property1 { get; set; }

    public string Property2 { get; set; }

    public int Property3 { get; set; }

    public List<Things> Things;
}

@Html.TextBoxFor(m => m.Property1)
@Html.TextBoxFor(m => m.Property2)
@Html.TextBoxFor(m => m.Property3)
<table>
    <tbody>
    @foreach (var thing in Model.Things)
    {
        <tr>
            <td>@thing.ID</td>
            <td>@thing.Name</td>
            <td><input type="submit" value="Select" name="Command" /></td>
        </tr>
    }
    </tbody>
</table>


[HttpPost]
public ActionResult TableSample(TableSample sample, string Command)
{
    if (Command == "Select")
    {
        //How to capture selected row ID?
    }

    if (Command == "Other")
    {

    }
}   
4

2 に答える 2

1

javascript を使用して、送信ボタンのクリックをキャッチし、行 ID を非表示フィールドに配置します。これにより、残りのフィールドと共に送信されます。

行 ID がモデルの一部ではない場合は、非表示フィールドと同じ名前のパラメーターをアクション メソッドに追加するだけです。

詳細が必要な場合はお知らせください。mvc アプリケーションの 1 つで、基本的に同じことを行いました。

基本的に3つのステップ:

1) 非表示の入力を追加します。フィールドはモデルの一部ではないため、ヘルパーではなく単純な HTML を使用します。これを次の形式のどこかに配置します。

<input type="hidden" id="rowId" name="rowId" />

2) 新しいパラメーターを含めるようにアクション メソッドのシグネチャを変更します (整数であると仮定しますが、そうでない場合はそれに応じて型を変更できます)。

public ActionResult TableSample(TableSample sample, string Command, int rowId)

3) 送信ボタンのクリックをキャッチする JavaScript を追加し、行 ID を非表示フィールドに配置します。私は jQuery を好みますが、MVC 4 ではかなり標準的なので、jQuery にアクセスできると思います。

$(function () {

    $('input[name="command"]').click(function () {

        // because there is a command button on each row it is important to
        // retrieve the id that is in the same row as the button
        $('#rowId').val($(this).parents('tr:first').children('td:first').html());

    });

});
于 2013-08-06T19:20:04.537 に答える