ASP.NET MVC 2 Beta を使用しています。スティーブン サンダーソンのテクニック (彼の著書 Pro ASP.NET MVC フレームワーク) を使用してウィザードのようなワークフローを作成できますが、非表示のフォーム フィールドの代わりにセッションを使用してリクエスト間でデータを保持することを除きます。モデルがコレクションではない場合、ページ間を行き来し、TextBox の値を問題なく維持できます。例は単純な Person モデルです。
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public string Email { get; set; }
}
しかし、IEnumerable を渡すと、これを機能させることができません。私の見解では、モデルを実行して、リスト内の各人物の名前と電子メールの TextBox を生成しようとしています。フォームを正常に生成でき、値を含むフォームを送信してステップ 2 に進むことができます。しかし、ステップ 2 で [戻る] ボタンをクリックすると、フォームが空の状態でステップ 1 に戻ります。以前に入力したフィールドはありません。私が見逃しているものがあるに違いありません。誰か助けてくれませんか?
これが私の見解です:
<% using (Html.BeginForm()) { %>
<% int index = 0;
foreach (var person in Model) { %>
<fieldset>
<%= Html.Hidden("persons.index", index.ToString())%>
<div>Name: <%= Html.TextBox("persons[" + index.ToString() + "].Name")%></div>
<div>Email: <%= Html.TextBox("persons[" + index.ToString() + "].Email")%></div>
</fieldset>
<% index++;
} %>
<p><input type="submit" name="btnNext" value="Next >>" /></p>
<% } %>
そして、ここに私のコントローラーがあります:
public class PersonListController : Controller
{
public IEnumerable<Person> persons;
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
persons = (Session["persons"]
?? TempData["persons"]
?? new List<Person>()) as List<Person>;
// I've tried this with and without the prefix.
TryUpdateModel(persons, "persons");
}
protected override void OnResultExecuted(ResultExecutedContext filterContext)
{
Session["persons"] = persons;
if (filterContext.Result is RedirectToRouteResult)
TempData["persons"] = persons;
}
public ActionResult Step1(string btnBack, string btnNext)
{
if (btnNext != null)
return RedirectToAction("Step2");
// Setup some fake data
var personsList = new List<Person>
{
new Person { Name = "Jared", Email = "test@email.com", },
new Person { Name = "John", Email = "test2@email.com" }
};
// Populate the model with fake data the first time
// the action method is called only. This is to simulate
// pulling some data in from a DB.
if (persons == null || persons.Count() == 0)
persons = personsList;
return View(persons);
}
// Step2 is just a page that provides a back button to Step1
public ActionResult Step2(string btnBack, string btnNext)
{
if (btnBack != null)
return RedirectToAction("Step1");
return View(persons);
}
}