【发布时间】:2017-05-18 15:56:04
【问题描述】:
我的观点是呈现为文本框、下拉列表和复选框的问题集合。这些问题存储在数据库中。
对于我的观点,我创建了一个视图模型
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 个选择选项(是、否、--select--)。根据页面加载 ddlMYddl 的 DB 回答,应该选择“是”,但我得到 --Select--
我哪里错了
【问题讨论】:
标签: c# jquery html asp.net-mvc