0

I have written a simple jquery dialog to save two fields to db. However for easiness in the controller it does not actually save to db instead it creates a mock object and returns it as json to client.

The the form code is

<input type="button" name="name" value="New Entry Dialog" id="newDialog"/>
    <div id="frm2" style="display:none">
    <table>
    <thead>
        <tr>
            <td></td>
            <td></td>
            <td></td>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>@Html.LabelFor(x => x.emp.FirstName, new { @class = "form-control"})</td>
            <td>@Html.TextBoxFor(x => x.emp.FirstName, new { @class = "form-control", id="firstName" })</td>
            <td>@Html.ValidationMessageFor(x => x.emp.FirstName)</td>
        </tr>
         <tr>
            <td>@Html.LabelFor(x => x.emp.LastName, new { @class = "form-control" })</td>
            <td>@Html.TextBoxFor(x => x.emp.LastName, new { @class = "form-control", id="lastName" })</td>
            <td>@Html.ValidationMessageFor(x => x.emp.LastName)</td>
        </tr>
         <tr>
            <td></td>
            <td></td>
            <td>
                <input type="button" value="Save" class="btn btn-success" id="saveDialog"/>
                <input type="reset" value="close" class="btn btn-success" id="closeDialog"/>
            </td>
        </tr>
    </tbody>
</table>
        </div>

JQUERY for the dialog, input validations and send to db:

@section Scripts {
    <script>


        $(document).ready(function () {


            //POST 2
            var form = $('#frm');

            //the dialog and validations (reparsing the validaotor)
            $('#frm2').dialog({
                title: 'new entry',
                modal: true,
                width: 600,
                heigth: 400,
                draggable: false,
                resizable: false,
                closeOnEscape: true,
                autoOpen: false,
                show: { effect: "scale", duration: 200 },
                open: function (event, ui) {
                    $(this).load(function (html) {
                        var form = $('#frm2');
                        form.data('validator', null);
                        $.validator.unobtrusive.parse(form);

                        //$('#form1', html).submit(function () {
                        //    $.ajax({
                        //        url: this.action,
                        //        type: this.method,
                        //        data: $(this).serialize(),
                        //        success: function (res) {
                        //            if (res.success) {
                        //                $('#frmDetails').dialog('close');
                        //            }
                        //        }
                        //    });
                        //    return false;
                        //});
                    });
                }

            });

            $('#newDialog').click(function () {
                $('#frm2').dialog('open');
            });

            //save to db
            $('#saveDialog').click(function (evt) {

                var x = {'FirstName': $('#firstName').val(), 'lastName':$('#lastName').val()};
                $.ajax({
                    url: '@Url.Action("Save", "Employee")',
                    method: 'post',
                    data: JSON.stringify({ 'em': x }),
                    contentType: 'application/json; charset=utf-8',
                    dataType: 'json',
                    success: function (data) {
                        alert('record saved');
                    },
                    error: function () { alert('error');}
                });
            });

here is my model

public class EmployeeModel
{
    public int EmpID { get; set; }

    [Required]
    public string FirstName { get; set; }

    [Required]
    public string LastName { get; set; }
}

here is the controller and action for save

[HttpPost]
public ActionResult Save(EmployeeModel em)
{
    try
    {
        if (ModelState.IsValid)
        {
            // TODO: Add insert logic here
            EmployeeModel e = new EmployeeModel { FirstName = em.FirstName, LastName = em.LastName };
            return Json(e, JsonRequestBehavior.AllowGet);    
        }

        return View();

    }
    catch
    {
        return View();
    }
}

save to db works and server side validation also successful but the client side validation does not show errors on the dialog. How do i correct my code?

here is the video

Phill Greggan
  • 2,234
  • 3
  • 20
  • 33

1 Answers1

2

In order for client side validation to work, you need to have the inputs inside a <form> element. Change your

<div id="frm2" style="display:none">

to

<form id="frm2" style="display:none">
  • validation started to work again such as when i remove text from input fields it shows errors but when i click "save" when fields empty it stopped the client side validation and server side took over, why this happened? – Phill Greggan Jan 14 '16 at 04:05
  • Because the "Save" button is not a submit button :) –  Jan 14 '16 at 04:07
  • A few options. Keep it as it but in the `.click()` handler, test `if(form.IsValid()) { // make ajax call } else { // do nothing? }` or change it to a `type="submit"` but cancel the action in the handler. –  Jan 14 '16 at 04:09
  • thanks its works but one more why it still submits to the server even the client validation took place – Phill Greggan Jan 14 '16 at 04:10
  • 1
    Did you check for `form.IsValid()`? Also, it does not appear that your dynamically loading the form after the view has been loaded so re-parsing the validator is not necessary (although its not clear what `$(this).load(function (html) {` is actually doing) –  Jan 14 '16 at 04:12
  • i a have posted a datatable related question on jquery http://stackoverflow.com/questions/34781366/why-render-of-jquery-datatable-does-not-execute – Phill Greggan Jan 14 '16 at 04:14
  • yea in this case don't need re-parsing validator it works without it too : ) – Phill Greggan Jan 14 '16 at 04:16
  • I'll add some comments to you other question shortly :) –  Jan 14 '16 at 04:17
  • i appreciate your commitment to guide new web developers. is there a way to enable stackoverflow chat with you so some questions can be discussed outside of main topic 'cus it gets flooded. – Phill Greggan Jan 14 '16 at 04:21
  • Refer [this link](http://stackoverflow.com/help/privileges/chat-rooms) fr creating a chat room. But I'm not sure that its intended for asking and answering specific questions - more a for general discussion about a topic. When I get a chance, I check on meta what the expectation are for its usage. –  Jan 14 '16 at 04:56