C# 在@foreach内绑定每个DropDownListFor
以我的ASP.NET WebForms经验,这是我的第一个MVC项目。C# 在@foreach内绑定每个DropDownListFor,c#,asp.net-mvc,C#,Asp.net Mvc,以我的ASP.NET WebForms经验,这是我的第一个MVC项目。 这里有一个我认为机制不允许的问题,但我可能错了。 在@foreach中有一个DropDownListFor并不是那么简单。 首先,下拉列表没有选择我传递给它的值(m=>question.Answer)——请注意,在下图中,它们都显示了无答案,因为它没有选择我加载的正确值。 其次,由于它们都以相同的表单字段名结束,控制器如何将它们重新划分到相应的列表中? 我已经看了一个小时,并搜索了一个类似的例子,但我找不到任何例子。 有什么
这里有一个我认为机制不允许的问题,但我可能错了。
在
@foreach
中有一个DropDownListFor
并不是那么简单。首先,下拉列表没有选择我传递给它的值(
m=>question.Answer
)——请注意,在下图中,它们都显示了无答案
,因为它没有选择我加载的正确值。其次,由于它们都以相同的表单字段名结束,控制器如何将它们重新划分到相应的列表中?
我已经看了一个小时,并搜索了一个类似的例子,但我找不到任何例子。
有什么好的解决方案不是硬编码的黑客或变通方法 型号:
public List<SelectListItem> PossibleAnswers
{
get
{
return new List<SelectListItem>()
{
new SelectListItem() { Text = "No Answer", Value = "0" },
new SelectListItem() { Text = "Very Bad", Value = "1" },
new SelectListItem() { Text = "Bad", Value = "2" },
new SelectListItem() { Text = "Average", Value = "3" },
new SelectListItem() { Text = "Good", Value = "4" },
new SelectListItem() { Text = "Very Good", Value = "5" }
};
}
}
public enum SurveyAnswer
{
NoAnswer,
VeryBad,
Bad,
Average,
Good,
VeryGood
}
public class SurveyQuestionClass
{
public int ID { get; set; }
public string Question { get; set; }
public SurveyAnswer Answer { get; set; }
}
public List<SurveyQuestionClass> QuestionsAnswers { get; set; }
公共列表可能的答案
{
得到
{
返回新列表()
{
新建SelectListItem(){Text=“无答案”,Value=“0”},
新建SelectListItem(){Text=“非常糟糕”,Value=“1”},
新建SelectListItem(){Text=“Bad”,Value=“2”},
新建SelectListItem(){Text=“Average”,Value=“3”},
新建SelectListItem(){Text=“Good”,Value=“4”},
新建SelectListItem(){Text=“非常好”,Value=“5”}
};
}
}
公共普查员
{
不回答,
维里巴德,
不好,,
平均,
好,,
非常好
}
公共课堂调查问题课堂
{
公共int ID{get;set;}
公共字符串问题{get;set;}
公共调查回答{get;set;}
}
公共列表问题服务器{get;set;}
视图:
@foreach(Model.QuestionsAnswers中的变量问题)
{
@Html.DropDownListFor(m=>question.Answer,Model.PossibleAnswers,新的{style=“font size:small;”})
@Html.Raw(question.question)
}
看起来是这样的:
@model SurveyQuestionClass
<tr>
<td>
@Html.DropDownListFor(m => m.Answer, Model.PossibleAnswers, new { style = "font-size: small;" })
</td>
<td>
@Html.Raw(Model.Question)
</td>
</tr>
您应该使用editortemplates 这可应用于以下情况: 将您可能的答案移至SurveyQuestionClass。然后您可以像这样指定editortemplate:
@model SurveyQuestionClass
<tr>
<td>
@Html.DropDownListFor(m => m.Answer, Model.PossibleAnswers, new { style = "font-size: small;" })
</td>
<td>
@Html.Raw(Model.Question)
</td>
</tr>
当您将模型返回控制器功能时,所有问题和答案都将绑定到问题解答列表。遍历列表并阅读SurveyQuestionClass.Answer属性,将为您提供问题答案您应该使用editortemplates 这可应用于以下情况: 将您可能的答案移至SurveyQuestionClass。然后您可以像这样指定editortemplate:
@model SurveyQuestionClass
<tr>
<td>
@Html.DropDownListFor(m => m.Answer, Model.PossibleAnswers, new { style = "font-size: small;" })
</td>
<td>
@Html.Raw(Model.Question)
</td>
</tr>
当您将模型返回控制器功能时,所有问题和答案都将绑定到问题解答列表。遍历列表并阅读SurveyQuestionClass.Answer属性将为您提供问题答案