我必须在网页上实现多个单选按钮列表(ASP.NET MVC 4)。为此,我使用了编辑器模板。
这是代码:
public class Evaluation
{
public List<Question> Questions { get; set; }
public Evaluation()
{
Questions = new List<Question>();
}
}
public class Question
{
private string _name;
private string _translationText;
public int LocalizationID { get; set; }
public string Name
{
get { return _name; }
set { _name = value; }
}
public string TranslationText
{
get
{
if (String.IsNullOrEmpty(_translationText))
{
return _name;
}
else
return _translationText;
}
set { _translationText = value; }
}
public List<Answer> Answers { get; set; }
[Required]
public int SelectedAnswer { get; set; }
public int Order { get; set; }
public Question()
{
Answers = new List<Answer>();
}
}
控制器
[HttpGet]
public ActionResult Index()
{
try
{
var evaluation = _service.GetEvaluation();
return View(evaluation);
}
[HttpPost]
public ActionResult Index(Evaluation model)
{
if (!ModelState.IsValid)
{
//Save Evaluation
}
retrun View(model);
}
如果模型无效,那应该在模型的主视图中返回我。但模型并不完整,仅包含 LocalizationID 和 SelectedAnswer 的信息:
看法
索引.chtml
@model Evaluation
@using (Html.BeginForm())
{
@Html.ValidationSummary()
@Html.HiddenFor(x=>x.Questions)
@Html.EditorFor(x=>x.Questions)
<p>
@Html.Raw(Html.GenerateCaptcha())
@Html.ValidationMessage("recaptcha")
</p>
<input type="submit" value="@T("Save_Answer")"/>
@Html.ValidationMessage("ERROR_SURVEY")
}
在编辑器模板中:
@model Question
<div id="@Model.LocalizationID">
@Html.HiddenFor(x=>x.LocalizationID)
<h3>@Model.Order. @Model.TranslationText</h3>
@if (Model.Order == 1)
{
<p>
@Html.DropDownListFor(b => b.SelectedAnswer,new SelectList(Model.Answers,"LocalizationID","TranslationText"))
</p>
}
else
{
foreach (var a in Model.Answers)
{
<p>
@Html.RadioButtonFor(b=>b.SelectedAnswer, a.LocalizationID ) @a.TranslationText
</p>
}
}
@Html.ValidationMessageFor(x=> x.SelectedAnswer)
</div>
因为我是 ASP.NET MVC 的新手,所以我从以下代码中获取了代码:ASP.NET MVC 3 Radio Button Strongly typed
有什么办法可以找回我的模型吗?我需要它来避免刷新我的页面并丢失所选选项。
谢谢,