My app requires the ability to send emails on multiple views. I'm trying to use a View Component so I can reuse my logic multiple places. When the user clicks the Send button I don't want to refresh the entire view...I want to validate the form and display any model errors, else send the email.
The setup below works fine for Client Side validation, but I'm not sure how to bring back the model errors server side and display them in the view. Any help is appreciated.
Default.cshtml (View Component - using jquery-ajax-unobtrusive)
@model EmailViewModel<div id="Email"><div class="row section-buffer"><div class="col-sm-12"><span class="section-header">Email</span></div></div><hr /><form id="EmailForm" method="post" class="form-horizontal" asp-controller="Email" asp-action="Send" data-ajax="true" data-ajax-method="POST" data-ajax-success="sendEmailSuccess" data-ajax-failure="sendEmailFailure(xhr, status, error)" data-ajax-update="Email"><div class="form-group form-group-sm"><label class="description-label col-sm-3" asp-for="From"></label><div class="col-sm-9"><input class="form-control" asp-for="From" /><span asp-validation-for="From" class="text-danger"></span></div></div><!-- remaining fields omitted --><div class="form-group form-group-sm"><div class="col-sm-9 col-sm-offset-3"><button type="submit" class="btn btn-primary">Send</button></div></div></form></div>
EmailViewModel
public class EmailViewModel { [Required] public string From{ get; set; } //remaining properties omitted }
EmailController
[HttpPost] [Route("/email/send")] public ActionResult Send(EmailViewModel viewModel) { if (!ModelState.IsValid) { //how do return my model errors back to my View Component? } else { //do send logic here return Content("Success"); } }