自分が抱えている問題を明確に述べるのは難しい。検証が失敗した後、ループで作成されたフォーム フィールドの値を保持する方法を理解しようとしています。ループと検証で作成された一連の要素を持つ、より複雑な現実世界のフォームがあります。以下に含まれる簡単な例にまとめました。
検証が失敗した場合、ループで作成された「コメント」という名前のテキストエリアに、下の送信前の画像に示されている値を保持したいと思います。
フォーム送信をデバッグすると、各フィールドの値が、モデル内にある Comment という名前の IList 変数に正常に接続されます。これは私が欲しいものなので、ループしてインデックスに基づいてそれらを見つけることができます。
送信後、ループによって生成された各テキストエリアには、モデル内の IList 変数 Comment のコンマ区切り表現が表示されます。ビューとモデルのフィールドは、名前が同じであるため接続しているように見えます。それらは途中で正しく接続されますが、途中では接続されません。リスト全体ではなく、Comment[i] に関連付けられた値のみをビューに表示して、フォームの送信間で値が一定に保たれるようにしたいと思います。最初の読み込みの
下のスクリーンショットとサンプル コード:
送信前のフォームの変更:最初の送信後に表示されるフォーム: 2 回目の送信後に表示されるフォーム:モデル コード
using System.Collections.Generic;
namespace UI.Models.Forms
{
public class TempListModel : ContentModel
{
public TempListModel()
{
Comment = new List<string>();
}
public IList<string> Comment { get; set; } //Comments for each URL in the list
}
}
コードを表示
@model UI.Models.Forms.TempListModel
@using (Html.BeginForm("temptest", "Test", new { id = 1 }, FormMethod.Post, new { id = "listForm", name = "listForm" }))
{
<ul>
@for (int i = 0; i < Model.Comment.Count(); i++)
{
<li>
<div class="llformlabel">
Notes:
<div>@Model.Comment[i]</div>
@Html.TextArea("Comment", Model.Comment[i], 4, 63, new { @id = "Comment_" + i, @title = "Comment" })</div>
</li>
}
</ul>
<input type="submit" value="Save Changes" />
}
コントローラーコード
using System.Collections.Generic;
using System.Web.Mvc;
using UI.Models.Forms;
namespace UI.Controllers
{
public class TestController : Controller
{
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult TempTest(TempListModel model)
{
//This function executes after the user submits the form.
//If server side validation fails then the user should be shown the form as it was when they submitted.
//model.Comment = GetComments(); //In my real world example this comes from a database.
if (true) //!ModelState.IsValid) //In my real world code this is a validation step that may fail
{
return View(model);
}
}
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult TempTest(int? id)
{
//In the real world example there is a lot going on in this function.
//It is used to load data from databases and set up the model to be displayed.
var model = new TempListModel();
model.Comment = GetComments();
return View("TempTest", "TempLayout", model);
}
private static IList<string> GetComments()
{
//Simple sample function used for demo purposes.
IList<string> comments = new List<string>();
comments.Add("Comment 1");
comments.Add("Comment 2");
comments.Add("Comment 3");
return comments;
}
}
}