I solved this by creating a partial view for the sub model and then dynamically inserting those (with JavaScript/jQuery) as needed.
Accessing sub model with HTML Helper
-
08-10-2022 - |
質問
I have an object which looks like this:
public class QuestionSet
{
[Required]
public int Id { get; set; }
[Required]
public int ConferenceId { get; set; }
[Required]
public string Name { get; set; }
public virtual ICollection<RegistrationQuestion> Questions { get; set; }
public virtual ICollection<QuestionSetAssignee> QuestionSetAssignees { get; set; }
public QuestionSet()
{
}
public QuestionSet(int conferenceId)
{
this.ConferenceId = conferenceId;
}
}
And the model for RegistrationQuestion looks like this:
public class RegistrationQuestion
{
[Required]
public int Id { get; set; }
[Required]
public int QuestionSetId { get; set; }
[Required]
public string QuestionText { get; set; }
}
When creating a QuestionSet, I would like to create its related RegistrationsQuestions at the same time. However, the Razor Html Helpers don't let me drill down to that level.
I can do this:
@Html.LabelFor(model => model.Questions)
but not this (and this is what I want to be able to do):
@Html.LabelFor(model => model.Questions.QuestionText)
Any guidance on how to achieve this?
解決 2
他のヒント
You can get it working like this. I made small changes to your model, instead of using ICollection<>, I used IList<> which have indexer support and can easily be iterated.
public class QuestionSet
{
[Required]
public int Id { get; set; }
[Required]
public int ConferenceId { get; set; }
[Required]
public string Name { get; set; }
public virtual IList<RegistrationQuestion> Questions { get; set; }
}
public class RegistrationQuestion
{
[Required]
public int Id { get; set; }
[Required]
public int QuestionSetId { get; set; }
[Required]
public string QuestionText { get; set; }
}
I add following sample data in controller action -
public ActionResult Index()
{
QuestionSet q = new QuestionSet();
q.Questions = new List<RegistrationQuestion>();
q.Questions.Add(new RegistrationQuestion() { QuestionText = "hi1?" });
q.Questions.Add(new RegistrationQuestion() { QuestionText = "hi2?" });
q.Questions.Add(new RegistrationQuestion() { QuestionText = "hi3?" });
return View(q);
}
And then in your view, you can have iteration in following way -
@for (int i = 0; i < Model.Questions.Count; i++)
{
@Html.LabelFor(model => model.Questions[i].QuestionText, Model.Questions[i].QuestionText)
@Html.EditorFor(model => model.Questions[i].QuestionText)
<br/>
}
Output -
所属していません StackOverflow