我一直在抨击墙壁试图让EditorFor按照here所述的方式工作,但我不能为我的生活让我的版本工作。
我有两个ViewModel:
InterviewViewModel
public class InterviewViewModel
{
...
public List<QuestionViewModel> Questions { get; set; }
}
和 QuestionViewModel :
public class QuestionViewModel
{
public int QuestionId { get; set; }
public string QuestionName { get; set; }
...
}
我尝试在两个地方创建EditorTemplates,
/Views/Interview/EditorTemplates/QuestionViewModel.cshtml
和
/Views/Shared/EditorTemplates/QuestionViewModel.cshtml
似乎都没有做任何事情。
public ActionResult MyClass(int id = 0)
{
using (RRContext db = new RRContext())
{
...
List<QuestionModel> questionModels = new List<QuestionModel>();
questionModels = db.QuestionModels.ToList();
...
viewModel.Questions = questionViewModels;
return View(viewModel);
}
}
@model ResidentRank.Models.Interview.InterviewViewModel
... (html.beginform is here)
Html.EditorFor(model => model.Questions);
@model ResidentRank.Models.Interview.QuestionViewModel
<div style="clear:both; margin:10px 0px;">
<label>@Html.DisplayFor(m => m.QuestionName)</label>
@Html.DropDownListFor(m => m.SelectedQuestionOption, Model.OptionSelector)
</div>
在我脑海中徘徊的问题是“为什么这不起作用?!”
答案 0 :(得分:2)
在HomeController中
[HttpGet]
public ActionResult Display(int id = 0)
{
var questionViewModel = new InterviewViewModel {
Questions =
new List<QuestionViewModel>()
{
//Hard coded values to represent data coming from db i.e db.QuestionModels.ToList();
new QuestionViewModel() {QuestionId = 1, QuestionName = "A"},
new QuestionViewModel() {QuestionId = 2, QuestionName = "B"}
}
};
return View(questionViewModel);
}
的ViewModels
public class InterviewViewModel {
public List<QuestionViewModel> Questions { get; set; }
}
public class QuestionViewModel {
public int QuestionId { get; set; }
public string QuestionName { get; set; }
}
\视图\主页\ Display.cshtml
@model MvcApplication1.Models.Interview.InterviewViewModel
@using (Html.BeginForm())
{
<fieldset>
@Html.EditorFor(x => x.Questions)
<input type="submit" value="Save" />
</fieldset>
}
\ Views \ Shared \ EditorTemplates \ QuestionViewModel.cshtml
确保这是部分视图。
@model MvcApplication1.Models.Questions.QuestionViewModel
<div style="clear:both; margin:10px 0px;">
<label>@Html.DisplayFor(m => m.QuestionName)</label>
</div>
请注意,我删除了
@Html.DropDownListFor(m => m.SelectedQuestionOption, Model.OptionSelector)
用于保持视图简单。
显示..