たくさんのテキスト ボックスを含む MVC フォームを作成しています。ただし、私のモデルには文字列のリストが必要です。私がやろうとしているのは、ユーザーが送信を押すと、フォームが投稿される前に、テキスト ボックス内のすべての値を取得し、それをリストに追加して送信用のモデルに追加することです。どうすればこれができるのか、私は立ち往生していますか?
これを行う必要がある理由は、フィールドの数が増える可能性があり、ページがそれに適応するという点で、フォームを動的にする必要があるためです。モデルはフォームの長さに適応する必要があるため、個々のフィールドをモデルにハードコードすることはできません。
これまでの私のコードは次のとおりです。
HTML
@using (Html.BeginForm(new { id = "feedbackForm" }))
{
<fieldset>
@foreach (Feedback_Num_Questions questionForm in FeedbackSurveyQuestions)
{
string textBoxID = "feedbackq";
questionNumberTextBoxes++;
textBoxID = textBoxID + questionNumberTextBoxes.ToString();
<input type="text" id="@textBoxID" />
}
<input type="text" id="txtAdditionalComments" />
<input type="submit" value="Create" name="btnFeedbackSubmit" id="btnSubmitFeedbackForm" />
</fieldset>
}
モデル:
public class PostCourseFeedbackModel
{
public List<string> responseList { get; set; }
public decimal pelID { get; set; }
public string employeeid { get; set; }
}
助けてくれてありがとう!
更新: FLEM から応答を得た後、コードを少し修正しました。まだ完全には機能していませんが、誰かが問題を発見できることを望んでいました:
HTML:
@using (Html.BeginForm(new { id = "feedbackForm" }))
{
<fieldset>
@{
int i = 0;
foreach (Feedback_Num_Questions questionForm in FeedbackSurveyQuestions)
{
i++;
string textBoxID = "feedbackq" + i.ToString();
@Html.TextBoxFor(m => m.responseList[i], new { @id = textBoxID });
}
<input type="submit" value="Create" name="btnFeedbackSubmit" id="btnSubmitFeedbackForm" />
}
</fieldset>
}
モデルは変わらず…
更新 - flem の要求に応じて、アクションを投稿しています。ただし、データで何をするつもりかをまだコーディングしていないため、これは必要最小限のアクションです...
[HttpPost]
public ActionResult PostCourseFeedback(PostCourseFeedbackModel feedback)
{
return RedirectToAction("FeedbackSubmitted", "Feedback", new { status = "success" });
}