我的观点是呈现为文本框,下拉列表和复选框的问题集合。这些问题存储在数据库中。
对于我的观点,我创建了一个viewmodel
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>
}
}
}
现在让我们说我的数据列表是一个是和否列表。这是我如何从数据库中获取我的值并将我的值传递给View
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工作
@Html.DropDownListFor(mod => mod.QuestionAnswerList[i].Answer, Model.QuestionAnswerList[i].DataList, "--Select--", new { @class = "form-control placeholder-color answers", style = "width: 150px;" })
总结一下。使用上面的代码呈现的下拉列表有3个选择选项(yes,no, - select--)。基于来自DB的页面加载答案ddlMYddl应选择“是”但我得到 - 选择 -
我哪里出错
答案 0 :(得分:0)
当您在MYMethod
时,您知道在创建列表时选择了哪个?如果是这样,您可以使用selected
的{{1}}属性并将其设置为true。
SelectedListItem