私のビューは、テキストボックス、ドロップダウン、およびチェックボックスとして表示される質問のコレクションです。これらの質問はデータベースに保存されます。私は今ここでのviewmodel動的HTML設定値の問題DropDownListFor MVC5
public class SpecialProgram
{
public string Role { get; set; }
public List<QuestionAnswer> QuestionAnswerList { get; set; }
// other prop
}
public class QuestionAnswer
{
// other prop
public int QuestionID { get; set; }
public string Question { get; set; }
public string ControlType { get; set; }
public int QuestionSortOrder { get; set; }
public string Answer { get; set; }
public IEnumerable<SelectListItem> DataList { get; set; }
}
を作成している私の見解については
は、私の見解
@model MyApplication.SpecialProgram
@using (Html.BeginForm("SavePage", "MyController", FormMethod.Post, new { enctype = "multipart/form-data", @id = "formData" }))
{
@for (int i = 0; i < Model.QuestionAnswerList.Count(); i++)
{
// other stuff......
else if (@Model.QuestionAnswerList[i].ControlType == "DropDown")
{
<div class="col-lg-12">
<div class="input-group" style="padding: .15em .15em .15em .15em">
<span class="input-group-addon" style="width:350px; text-align: left;">@Model.QuestionAnswerList[i].Question</span>
@Html.DropDownListFor(mod => mod.QuestionAnswerList[i].Answer, Model.QuestionAnswerList[i].DataList, "--Select--", new { @class = "form-control placeholder-color answers", style = "width: 150px;" })
</div>
</div>
}
}
}
今すぐ私のデータ一覧をはい&ませリストされていないと言うことができますです。ここでデータベースから値を取得して値を渡す方法を次に示します。
public List<QuestionAnswer> MYMethod()
{
List<QuestionAnswer> qadata = new List<QuestionAnswer>();
List<SelectListItem> YesNoList = new List<SelectListItem>();
YesNoList.Add(new SelectListItem { Text = "Yes", Value = "1" });
YesNoList.Add(new SelectListItem { Text = "No", Value = "0" });
qa.DataList = YesNoList;
// the qa.Answer here is 1. which is the selected dropdown value saved in db. I want yes to be pre-selected on page load. But for some reason On page load I get default value "--Select--"
}
テスト目的でのみ、値をドロップダウンに設定しようとしました。これは動作します
var data = '@Model.QuestionAnswerList[2].Answer';
$('#ddlMYddl').val(data)
しかし、jqueryを使用しても実際に私の問題は解決しません。私は@ Html.DropDownListForを働かせたいです
を要約します。上記のコードで表示されるドロップダウンには3つの選択肢があります(yes、no、--select--)。ページのロードのDBからの回答に基づいてddlMYddlが持つべき「はい」を選択したが、私はあなたがMYMethod
にいるとき、私は間違って
はい私はそれが動作することに気づいた。私の質問はなぜこの@ Html.DropDownListFor(mod => mod.QuestionAnswerList [i] .Answer、Model.QuestionAnswerList [i] .DataList、.....は動作しませんでした – DotNetBeginner