0

I am using Javascript serializer for passing model data to controller but this is not firing the code validation.
Here is the code

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/microsoftajax.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/MicrosoftMvcAjax.js")" type="text/javascript"></script>
<script type="text/javascript" language="javascript">

 $(document).ready(function () {

        $("#btnCreateDepartment").click(function () {

            var name = $('#txtDeptName').val();
            $.ajax({
                data: { modelName: 'DEPARTMENT', values: Sys.Serialization.JavaScriptSerializer.serialize(
                {
                    DeptName: name
                }
            )
                },
                url: '@Url.Action("Create", "Office")',
                type: "POST",
                complete: function (result) {
                    debugger
                    alert("complete");
                },
                error: function (result) {
                    debugger
                    alert(result.statusText);
                }
            }); //Endof ajax
            return false;
        }); //end of click

    });    // end of ready
</script>

In model the i have added validation as following

[Required(ErrorMessage = "Please Enter department")]
        public string DeptName { get; set; }

But this is not getting fired .

Chuck Norris
  • 15,207
  • 15
  • 92
  • 123
Rutu
  • 147
  • 2
  • 10
  • http://stackoverflow.com/questions/5200098/asp-net-mvc-3-ajax-form-submit-and-validation . hope it helps – hopper Mar 26 '12 at 09:15

2 Answers2

0

Passing the object via ajax to the controller will disable the default mvc validation form. This validation will only work if you do a normal post. Anyway if you want to use ajax you need to do the validation using jquery. If you decide not to use ajax then you can use mvc's built in validation. I also recommend fluent validation library for MVC

hopper
  • 4,230
  • 8
  • 36
  • 49
  • Thanks teahupoo i tried using validations using jquery by adding foll owing code to my view $.validator.addMethod("validateEvent", function () { alert("validating"); }) but this is not working – Rutu Mar 29 '12 at 11:23
0

Change data parameter of your jQuery ajax to

data: { DeptName: name },

so it contains only properties of your model. Other department properties should follow DeptName ex. { DeptName: name, DeptAddress: address, ... }.

If your mvc model was mirrored on client side as a javascript model department you would just go:

data: { JSON.stringify(department) },
veblock
  • 1,904
  • 18
  • 10