I am having issues with loading a ViewComponent from a controller, my main view is Contact.cshtml and my ViewComponent is AddContact.cshtml. AddContact is a simple form with a submit button, I am trying to get it so that when the model is invalid, the component refreshes with the data that was entered and the model validation messages.
The problem is when I return "ViewComponent("AddContact", newContact)" in the controller with then invalid model 'newContact', it reloads the ViewComponent in an entirely new page and not as a partial in the Contact view. Is there some syntax I am missing or would this require something else entirely?
Contact.cshtml:
@await Component.InvokeAsync("AddContact", new { addContact = newContactModel })
AddContact.cshtml
@using (Html.BeginForm("AddContact", "Contact", FormMethod.Post))
{
....
<input id="addContactBtn" type="submit" value="Add" class="btn btn-success">
}
Controller:
[HttpGet]
public ActionResult AddContact()
{
return ViewComponent("AddContact");
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddContact(AddContact_VM newContact)
{
if (!ModelState.IsValid)
{
return ViewComponent("AddContact", newContact);
}
OperationStatus opStat = granteeRepo.AddContact(newContact);
return View("Contact");
}
Component:
public class AddContact : ViewComponent
{
public IViewComponentResult Invoke(AddContact_VM newContact)
{
return View("AddContact", newContact);
}
}