9

On the jquery postback if the model state is invalid I want to show the validation error messages using jquery unobtrusive validation. I have created a sample application. The viewmodel in the application is as below

 public class CityModel
{
    public int Id { get; set; }

    [Display(Name = "City")]
    [Required(ErrorMessage = "City is required")]
    public string City { get; set; }
}

and the controller has the following action methods

 public ActionResult City()
    {
        var cities = GetCities();

        return View(cities);
    }

    [HttpPost]
    public ActionResult SaveCity(CityModel cityModel)
    {
        if (ModelState.IsValid)
        {
            //Save City
            return null;
        }
        else
        {
            return View();
        }
    }

public List<CityModel> GetCities()
    {
        var citiesList = new List<CityModel>
        {
            new CityModel() {Id = 1, City = "London"},
            new CityModel() {Id = 2, City = "New York"}
        };
        return citiesList;
    }

The views have the following mark ups

@model List<CityModel>
<h2>Cities</h2>

@Html.ValidationSummary(true)
@using (@Html.BeginForm(null, null, FormMethod.Post, new { id = "frmSite", name = "frmSite" }))
{
@Html.EditorForModel()

<input type="submit" name="Sumbit" onclick=" SaveCity(); return false; " />
}

<script>
function SaveCity() {       
    $.ajax({
        type: "POST",
        url: "/Home/SaveCity",
        contentType: "application/html; charset=utf-8",
        data: {
            Id: $('.cityId').val(),
            City: $('.cityName').val()
        },
        success: function (data) {
        }

    });
}   
 </script>

And the editor template looks like

@model CityModel
<table class="table">
    <tr>
        <td>
            @Html.TextBoxFor(x => x.Id, new {@class = "cityId"})
        </td>
    </tr>
    <tr>
        <td>
            @Html.TextBoxFor(x => x.City, null, new {@class = "cityName"})
            @Html.ValidationMessageFor(x => x.City)
        </td>
    </tr>
</table>

I have checked the <script src="/Scripts/jquery-1.10.2.js"></script> <script src="/Scripts/jquery.validate.js"></script> <script src="/Scripts/jquery.validate.unobtrusive.js"></script> are included in the page and <add key="UnobtrusiveJavaScriptEnabled" value="true" /> is present in the web config file

hutchonoid
  • 32,982
  • 15
  • 99
  • 104
rumi
  • 3,293
  • 12
  • 68
  • 109
  • did you set `@Html.ValidationSummary(true)` in your form? – Manoz Mar 11 '15 at 13:24
  • yes. Its set to true – rumi Mar 11 '15 at 13:27
  • isn't it `content: "application/html; charset=utf-8",` should be `contentType:"application/json; charset=utf-8"`. – Jai Mar 11 '15 at 13:28
  • @Jai yes. I changed it but that does not make any difference. I m getting the data in the model in the action method. Updated the question as well. – rumi Mar 11 '15 at 13:32
  • do you have the fields inside a form because unobtrusive validation will work if the fields are present inside a form and you have to validate the form like the answer in this post- http://stackoverflow.com/a/11469666/3748701 – Manik Arora Mar 11 '15 at 13:40
  • I have tried wrapping the fields inside a form but still it does not make a difference. Also I have changed the contentType back to `contentType: "application/html; charset=utf-8",` as contentType: "application/json; charset=utf-8", does not call the action method – rumi Mar 11 '15 at 14:14

1 Answers1

17

You are calling your post via ajax so you will need to manually call $form.validate(); and test the result with $form.valid():

function SaveCity() {

    $.validator.unobtrusive.parse($form);
        $form.validate();
        if ($form.valid()) {

        $.ajax({
            type: "POST",
            url: "/Home/SaveCity",
            contentType:"application/json; charset=utf-8",
            data: {
            Id: $('.cityId').val(),
            City: $('.cityName').val()
            },
            success: function (data) {
            }

        });

    }
}

If it is purely client-side, the errors will be contained within the jquery validation object $form.validate().errorList but you will have to do some manual processing similar to what I mention below.

If you wish to return server-side model state you can add the model state errors as a key value pair in your controller and return them as json.

You can use the below method to display the messages.

This finds all the validation message spans with model state error keys and adds the red error message to them. Please note you may want to adapt this to display many error messages against a key.

public doValidation(e)
{
        if (e.data != null) {
            $.each(e.data, function (key, value) {
                $errorSpan = $("span[data-valmsg-for='" + key + "']");
                $errorSpan.html("<span style='color:red'>" + value + "</span>");
                $errorSpan.show();
            });
        }
}

Updated

Here is the above adapted so you can parse it manually from the jquery unobtrusive errors instead:

        $.each($form.validate().errorList, function (key, value) {
            $errorSpan = $("span[data-valmsg-for='" + value.element.id + "']");
            $errorSpan.html("<span style='color:red'>" + value.message + "</span>");
            $errorSpan.show();
        });

Just pop that in an else statement and you are good to go. :)

hutchonoid
  • 32,982
  • 15
  • 99
  • 104