2

コントローラに返す必要のあるデータの行がいくつかあるテーブルがあります。私の見解では、最初に期間を選択してボタンをクリックすることでテーブルをロードします。テーブルには関連するすべてのレコードが読み込まれますが、テーブルセルの1つにドロップダウンリストが含まれています。したがって、ドロップダウンで[更新]をクリックして選択できるはずです。コントローラーが変更を保存します。

だから私が保存しようとするまですべてが機能します。コントローラに送信されるモデルは完全にnullです。テーブルセルに関連付けたリストプロパティは、コントローラーnullに戻ります。

 @ModelType SuperViewModel
 //We need this a view model in order to store a List of the models in the table   

 @Using (Html.BeginForm())
 @For Each i in Model.CompleteList
    Dim currentItem = i //MVC auto-generated extra declarations. Seems redundant to me but it works.
 @<table>
 <tr>
 <td>@Html.DisplayFor(function(Model)currentItem.Name)</td>
 <td>@Html.DisplayFor(function(Model)currentItem.SampleTime)</td>
 <td>@Html.DropDownListFor(function(Model)currentItem.WorkTime, ViewBag.WorkTimeList)</td>
 </tr>
 Next
 </table>
 <input name="submit" type="submit" value="Update"/>
 End Using

 //Controller
 <HttpPost()>
 function Save(vmodel as SuperViewModel, submit as String) as ActionResult //NOTE: submit parameter is used because we have two submit buttons but its not relevant here
      if submit = "Update"
            db.Entry(vmodel.CompleteList).State = EntityState.Modified//Here the exception is throw because our list is null at this point even tho its tied to the model in the view.
            db.SaveChanges()
      end if
 End Function

注:これはVB.NETで記述されていますが、C#ヘルプは大歓迎です。私はMVCの両方の言語に精通しています。

4

3 に答える 3

2

forイテレータを使用し、ビューでHTML要素のインデックス付き要素を使用する必要があります。VB.NETの構文がわかりません。c#の例を以下に示します。これにより、モデルバインダーはビューモデル内の要素を正しく決定できるため、ポストバック時にビューモデルを再作成できます。

<table>
 @For(var i = 0; i < Model.CompleteList.Count; i++) 
{
 <tr>
 <td>@Html.DisplayFor(Model.CompleteList[i].Name)</td>
 <td>@Html.DisplayFor(Model.CompleteList[i]..SampleTime)</td>
 <td>@Html.DropDownListFor(Model.CompleteList[i]..WorkTime, ViewBag.WorkTimeList)</td>
 </tr>
}
 </table>

その後、postメソッドは正常に機能するはずです。

于 2012-04-24T02:15:56.900 に答える
0

によって生成されたマークアップの名前を確認する必要がありますが、これは、型に対してバインドしているDropDownListForためと思われますが、コントローラーメソッドは完全な型を想定しています。あなたが示したコードのどこにも、あなたがその型に結合しているのを見ることはありません。currentItemCompleteListSuperViewModelSuperViewModel

コントローラのメソッドを次のように変更してみてください。

<HttpPost()>
 function Save(currentItem as CompleteList, submit as String) as ActionResult //NOTE: submit parameter is used because we have two submit buttons but its not relevant here
      if submit = "Update"
            db.Entry(vmodel).State = EntityState.Modified//Here the exception is throw because our list is null at this point even tho its tied to the model in the view.
            db.SaveChanges()
      end if
 End Function

プロパティにはWorkTime、DropDownListから選択した値を入力する必要があります。

編集:バインディング名と一致するようにパラメーター名を変更しました。

于 2012-04-23T23:37:29.340 に答える
0

パラメータ名の競合が原因でnullが返される場合があります(使用されるパラメータ名は他の場所でも使用する必要があります)。これを試して

<input name="subButton" type="submit" value="Update"/>

と変更

function Save(vm as SuperViewModel, subButton as String) as ActionResult
于 2012-04-23T23:22:24.383 に答える