I was just trying out Unobtrusive ajax in .net core 2.0. I am trying the following model:
public class Blog
{
public int BlogId { get; set; }
[Required]
[Never(ErrorMessage = "Never say never")]
public string Url { get; set; }
public List<Post> Posts { get; set; }
class NeverAttribute : ValidationAttribute
{
public override bool IsValid(object value) => value.ToString() != "never";
}
}
I have generated a create partial view for this model, so it uses the default tag helpers. It submits to the following action:
public IActionResult AddBlog(Blog blog)
{
if (ModelState.IsValid)
{
context.Add(blog);
context.SaveChanges();
}
return Ok("done");
}
For a normal submit this would work as long as I do return View(blog)
. It would do the client side checks (check if url is empty) then submit to the server. Then, do the server side validation (check if url is "never") and display the error message without adding the data.
Now let's say using Unobtrusive ajax, I can add data-ajax=true
in my form. This checks the client side validation and submits. Once it validates the server side (NeverAttribute
), how do I display the message back on the form on fail?