0

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?

Neville Nazerane
  • 6,622
  • 3
  • 46
  • 79
  • For a start, your attribute should implement `IClientValidatable` and then write the scripts so you get client side validation. But in any case you must always validate on the server, if its invalid, you can return The `ModelState` errors and update the DOM (and do not use the obsolete `jquery.unobtrusive-ajax.js` - use `$.ajax` to post your form) –  Mar 30 '18 at 08:30
  • which event do I use `$.ajax` on? I did try an ajax send using `submit()` but it wouldn't stop if the js validations failed. also, any reason to not use unobtrusive ajax? it isn't really depreciated. – Neville Nazerane Mar 30 '18 at 10:19
  • 1
    You handle the forms `.submit()` event, cancel it, and check `.valid()` - `$(yourForm).submit(function(e) { e.preventDefault(); if (!$(this).valid()) { return; } // make you ajax call here });` –  Mar 30 '18 at 10:21
  • Refer also [The Complete Guide To Validation In ASP.NET MVC 3 - Part 2](https://www.devtrends.co.uk/blog/the-complete-guide-to-validation-in-asp.net-mvc-3-part-2) for how to implement client side validation for your `NeverAttribute` –  Mar 30 '18 at 10:24
  • great! the `.valid()` is something I was looking for as well. I am going through the link you send, i don't really find an option to set the validations back into the form – Neville Nazerane Mar 30 '18 at 11:07
  • `var errors = ModelState.Keys.Where(k => ModelState[k].Errors.Count > 0).Select(k => new { propertyName = k, errorMessage = ModelState[k].Errors[0].ErrorMessage });` will give you the data you need to pass back to the view (and then update the matching element generated by your ` –  Mar 30 '18 at 11:18
  • yeah, I have the code to serialize the errors. Was wondering if there was a built-in way to pass that into a form – Neville Nazerane Mar 30 '18 at 11:40
  • actually, I did may a complete serverside and js (and xamarin) library to serialize and display model state errors. After setting that up I noticed .net core has cleaner ways of doing something similar. Now i am trying to understand how much is provided by .net core before going to the next step – Neville Nazerane Mar 30 '18 at 11:48

0 Answers0