I have a table with a foreign key to another table.
I was able to create the MVC for the Create action but I can't seem to figure out the Update action.
I keep getting an error: An unhandled exception occurred while processing the request.
ArgumentNullException: Value cannot be null.
Parameter name: source
VM:
[Required]
[Display(Name = "Name")]
public string Name { get; set; }
[Required]
[Display(Name = "Description")]
public string Description { get; set; }
[Required]
[Display(Name = "Code before element including opening tag")]
public string Before { get; set; }
[Required]
[Display(Name = "Code after element including closing tag")]
public string After { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (Before == null || After == null)
yield return new ValidationResult("Custom HTML Before and Custom HTML After must be specified");
}
[Required]
[Display(Name = "HTML Element")]
public int HTMLElement { get; set; }
public ICollection<HTMLElement> HTMLElements { get; set; }
Controller:
[HttpGet]
public async Task<IActionResult> UpdateCustomizedHTMLElement(int Id)
{
var eElement = await db.CustomizedElements
.Include(e => e.HTMLElement)
.ThenInclude(e => e.Element)
.SingleOrDefaultAsync(w => w.Id == Id);
return View(eElement);
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult UpdateCustomizedHTMLElement(HTMLElement updateHTMLElement)
{
return View(updateHTMLElement);
}
View:
<div class="row justify-content-md-center">
<div class="col-sm-10 col-md-7 col-lg-6">
<h2>Update Customized HTML Element Type</h2>
<form method="post" asp-controller="Templates" asp-action="UpdateCustomizedHTMLElement">
<div class="form-group">
<label asp-for="Name"></label>:
<input class="form-control form-control-sm" type="text" asp-for="Name" />
<span class="text-danger" asp-validation-for="Name"></span>
</div>
<div class="form-group">
<label asp-for="Before"></label>:
<input class="form-control form-control-sm" type="text" asp-for="Before" />
<span class="text-danger" asp-validation-for="Before"></span>
</div>
<div class="form-group">
<label asp-for="HTMLElement"></label>:
@Html.DropDownListFor(m => m.HTMLElement, new SelectList(Model.HTMLElement.Element, "Id", "Element"), "", new { @class = "form-control" })
<span class="text-danger" asp-validation-for="HTMLElement"></span>
</div>
<div class="form-group">
<label asp-for="After"></label>:
<input class="form-control form-control-sm" type="text" asp-for="After" />
<span class="text-danger" asp-validation-for="After"></span>
</div>
<div>
<button class="btn btn-primary" type="submit" value="Submit">Save</button>
<button class="btn btn-secondary" type="button" value="Cancel" onclick="location.href='@Url.Action("HTMLElements", "Templates")'">Cancel</button>
</div>
</form>
</div>
</div>
What I have tried:
I have tried to Google "how to update a record with a foreign key property .net core" but haven't found anything that works.