3

私の質問は、テーブル データをビューからコントローラーに戻す方法です。

モデルにクラスがあります:

public class Company
{
    public string Name { get; set; }
    public int ID { get; set; }
    public string Address { get; set; }
    public string Town { get; set; }
}

そして、会社のリストを次のようにビューに渡します。

    @model IEnumerable<MyTestApp.Web.Models.Company>
    ....
    @using (Html.BeginForm("Edit", "Shop"))
    {
    <table id="example">
        <thead>
            <tr>
                <th>
                    @Html.DisplayNameFor(model => model.Name)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Address)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Town)
                </th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in Model) {
                <tr>
                    <td>
                        @Html.EditorFor(modelItem => item.Name)
                    </td>
                    <td>
                        @Html.EditorFor(modelItem => item.Address)
                    </td>
                    <td>
                        @Html.EditorFor(modelItem => item.Town)
                    </td>
                </tr>
            }   
        </tbody>
    </table>

    <input type="submit" value="Submit" />
}

すべて問題ないように見えますが、コントローラーで変更されたデータを取得する方法がわかりません。私はこれらのアプローチを使用しました:

public ActionResult Edit(IEnumerable<Company> companies)
    {
        // but companies is null
        // and ViewData.Model also is null

        return RedirectToAction("SampleList");
    }

変更されたオブジェクトにアクセスする必要があります。何が間違っていますか?

更新: webdeveloperのおかげで、「foreach」ループの代わりに「for」ループを使用する必要がありました。正しいバージョンは

<tbody>
        @for (int i = 0; i < Model.Count(); i++ ) {
            <tr>                   
                <td>
                    @Html.EditorFor(modelItem => modelItem[i].Name)
                </td>
                <td>
                    @Html.EditorFor(modelItem => modelItem[i].Address)
                </td>
                <td>
                    @Html.EditorFor(modelItem => modelItem[i].Town)
                </td>
            </tr>
        }   
    </tbody>
4

3 に答える 3

2

ここで私の答えを見てください:同じビュー内の複数のアイテムを更新するORダリン・ディミトロフの答え。

レンダリングされた html マークアップにindexin属性を持つ項目が必要です。nameまた、あなたは見ることができます:リストへのモデルバインディング

于 2013-01-22T08:25:22.723 に答える
1

Companyモデルを正しくバインドできるように、フォームにのIDが欠落していると思います。

次のように追加する必要があります。

@using (Html.BeginForm("Edit", "Shop"))
{
<table id="example">
    <thead>
        <tr>
            <th>
                @Html.HiddenFor(model => model.ID)
                @Html.DisplayNameFor(model => model.Name)
            </th>
            ...

それ以外の場合、コードの残りの部分は問題ないようです。

于 2013-01-22T07:52:24.420 に答える