GeekyNuns
GeekyNuns

Reputation: 298

JQuery validation is not working with ajax post

Can`t get why my JQuery validation is not working on my ProjectName field, it allows to post null values, may be the reason is that action is called with ajax and all the data are set without submitting the form? Here is my Model:

{
public class ProjectViewModel
{
    public int ProjectId { get; set; }

    [Required(ErrorMessage = "*")]
    [Display(Name = "project_name", ResourceType = typeof(Localization))]
    public string ProjectName { get; set; }

    [Display(Name = "project_description", ResourceType = typeof(Localization))]
    public string ProjectDescription { get; set; }

    [Display(Name = "system_kind", ResourceType = typeof(Localization))]
    public string SystemType { get; set; }

    [Display(Name = "project_manager", ResourceType = typeof(Localization))]
    public string ProjectManager { get; set; }

    [Display(Name = "project_type", ResourceType = typeof(Localization))]
    public string ProjectType { get; set; }

    [Display(Name = "fixed_bid", ResourceType = typeof(Localization))]
    public bool FixedBid { get; set; }

    [Display(Name = "TM", ResourceType = typeof(Localization))]
    public bool TimeAndMaterials { get; set; }

    public Nullable<System.DateTime> StartDate { get; set; }

    public Nullable<System.DateTime> TillDate { get; set; }
}

and the View I work on:

    @model BTGHRM.Models.ProjectViewModel

<link href="~/Content/themes/custom/MyCustom.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<script src="~/Scripts/jquery-ui.js"></script>


<script type="text/javascript">
    $(document).ready(function () {
        $("#postToServ").click(function () {

            var dataObject = {
                ProjectName: $("#ProjectName").val(),
                ProjectDescription: $("#ProjectDescription").val(),
                SystemType: $("#SystemType").val(),
                ProjectManager: $("#ProjectManager").val(),
                FixedBid: $("#FixedBid").val(),
                TimeAndMaterials: $("#TimeAndMaterials").val(),
                StartDate: $("#datepicker").val(),
                TillDate: $("#datepicker1").val()
            };

            $.ajax({
                url: "/Project/ProjectRegistration",
                type: "POST",
                data: dataObject,
                dataType: "json",
                success: function () {
                    $("#loading_content").html("<br><b>"+"@Resources.Localization.data_successfully_saved"+"!</b>");
                },
                error: function () {
                    alert("Unable to save! Try again");

                }
            });

        })
    })
</script>

<span class="content_h4">@Resources.Localization.register_project</span>
<br /><br />

    @using (Html.BeginForm(new { id="MyForm"}))
    {
        <table style="width:100%">
            <tr>
                <td style="width:20%">
                    <b>@Html.LabelFor(m => m.ProjectName):</b>
                </td>
                <td style="width:80%">
                    @Html.TextBoxFor(m => m.ProjectName, new { style = "width:80%"})
                    @Html.ValidationMessageFor(m => m.ProjectName, "", new { @class = "text-danger" })
                </td>
            </tr>
            <tr>
                <td>
                    @Html.LabelFor(m => m.ProjectDescription):
                </td>
                <td>
                    @Html.TextAreaFor(m => m.ProjectDescription, new { style = "width:80%; height:110px" })
                </td>
            </tr>
            //some similar code
    </table>
    <br />
    <div style="width:100%">
        <input type="button" id="postToServ" [email protected] style="position: absolute; top: 50%; left:50%;">
    </div>

}
<div id="loading_content"></div>

Upvotes: 1

Views: 50

Answers (1)

ADyson
ADyson

Reputation: 61849

This should work:

Points to note:

  1. Handle the "submit" event of the form instead of the button click

  2. Serialize the form using jQuery. Then you don't have to pick out each form element separately, or change your code when your fields change in future.

  3. Call the form validation method manually and check the outcome before making the ajax call.

  4. Additionally I've made the "error" function compliant with the jQuery documenation.

Replace

 <input type="button" id="postToServ" ...

with

<input type="submit" id="postToServ" ...

and then setup your script like this:

<script type="text/javascript">
$(document).ready(function () {
    $("#myForm").submit(function (event) {
      event.preventDefault(); //stop default postback behaviour

      var valid = $(this).valid(); //run form validation manually

      if (valid == true) {
        $.ajax({
            url: "/Project/ProjectRegistration",
            type: "POST",
            data: $(this).serialize(), // automatically read all the form data and convert to correct format for posting to server
            dataType: "json",
            success: function (response) {
                $("#loading_content").html("<br><b>"+"@Resources.Localization.data_successfully_saved"+"!</b>");
            },
            error: function (jQXHR, textStatus, errorThrown) {
              alert("An error occurred whilst trying to contact the server: " + jQXHR.status + " " + textStatus + " " + errorThrown);
            }
        });
       }
    });
});
</script>

Upvotes: 3

Related Questions