I have been working with C# MVC for while now but hadn't come across this scenario because my original project utilised database first development.
I have the following:
Model Class:
public partial class QuestionType : EntityBase
{
public string Type { get; set; }
}
public partial class Question : EntityBase
{
public string QuestionText { get; set; }
public virtual QuestionType QuestionType { get; set; }
}
public class EntityBase
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Display(Name = "Created")]
[DisplayFormat(DataFormatString = "{0:dd MMM yyyy h:m:s tt}")]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public DateTime Created { get; set; }
[Display(Name = "Last Updated")]
[DisplayFormat(DataFormatString = "{0:dd MMM yyyy h:m:s tt}")]
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime LastUpdated { get; set; }
}
In the contrtoller:
public IActionResult Create()
{
ViewBag.questionTypes = _context.QuestionTypes.ToList();
return View();
}
In the view:
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="QuestionText" class="control-label"></label>
<input asp-for="QuestionText" class="form-control" />
<span asp-validation-for="QuestionText" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="QuestionType.Id" class="control-label"></label>
<select asp-for="QuestionType.Id" asp-items="@(new SelectList(ViewBag.questionTypes,"Id","Type"))">
<option>Question Type:</option>
</select>
<span asp-validation-for="QuestionType.Id" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
And when collecting:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("QuestionText,QuestionType.Id")] Question question)
{
ViewBag.questionTypes = _context.QuestionTypes.ToList();
if (ModelState.IsValid)
{
}
return View(question);
}
Now this all works fine if I just use Id instead of QuestionType.Id but that would be leveraging the Id of the Question not the QuestionType and wouldn't work if there were numerous drop down lists. So how do I access the sub member "QuestionType.Id" because it doesn't bind when I reference it in the second create method.
Thanks in advance.