0

I am (finally) diving into JQuery and was wondering how to correctly handle validation of text inputs before posting. I have an ASPX page that will loop over a part of my model calling an User Control for each loop. I also have a JQuery Add link that will add a new (blank) User Control to the collection.

The page looks like:

    <h1>Create Document List</h1>

    <% Html.EnableClientValidation(); %>

    <% using (Html.BeginForm("CreateList", "Documents", FormMethod.Post, new { @class = "list", @enctype = "multipart/form-data" })) 
    { %>
        <%= Html.AntiForgeryToken() %>

        <div id="editorRows">
            <% foreach(var q in ViewData.Model.DocumentAndFileList)
                   Html.RenderPartial("DocEditRow", q);
            %>
        </div>
        <br />

        <%= Html.ActionLink("Add another...", "Add", null, new { id = "addItem" }) %>

        <br />
        <br />
        <br />

        <%= Html.SubmitButton("btnSave", "Save Document List")%>
        <%= Html.Button("btnCancel", "Cancel", HtmlButtonType.Button, "window.location.href = '" + Html.BuildUrlFromExpressionForAreas<DocumentsController>(c => c.Index()) + "';") %>
    <% } %>
</asp:Content>

The User Control looks like:

<div class="editorRow">
    <% using (Html.BeginCollectionItem("docs"))
       { %>

        <%= Html.Hidden("Document.Id", (Model != null) ? Model.Id : 0)%>

        <label for="Number">Document Name:</label>
        <%= Html.TextBox("Number", (Model != null) ? Model.Number : "", new { @size = "50", @maxlength = "255" })%>
        <%= Html.ValidationMessageFor(m => m.Number) %>

        &nbsp;

        <% if (Model != null && Model.FileName != null && Model.FileName.Length > 0)
           { %>
            <label>Current File:</label>
            <%= Model.FileName%>
        <% }
           else
           { %>
            <label>
                File Upload:
                <%= Html.FileBoxFor(m => m.HttpPostedFileBase)%>
            </label>
        <% } %>
        <a href="#" class="deleteRow">delete</a>
    <% } %>
</div>

I followed Scott Gu's advice on an old post of his on his blog. For some reason, I am not getting any validation. The previous devs on this project used a lot of JQuery so I am now trying to get JQuery validation to work but don't really know where to start. Googling seems to bring me to about 500 different ways to do this. Any pointers would be appreciated.

TIA


NOTE:

I have added the following to my page:

<asp:Content ID="myScript" ContentPlaceHolderID="pageScript" runat="server">
    <script type="text/javascript" language="javascript">
        $(document).ready(function () {
            $("#LoadDocs").validate();
            $.validator.unobtrusive.parse("#LoadDocs");
        });
    </script>
</asp:Content>

This seems to be partially working. If I add several new rows to my collection, only the first row will pop the message if the textbox is empty. I also added a

class="required"

to all of my inputs.

I am still struggling to get it to work 100% though. Any suggestions?

Keith Barrows
  • 24,802
  • 26
  • 88
  • 134
  • Have you seen this question : http://stackoverflow.com/questions/2500371/asp-net-mvc-enableclientvalidation-doesnt-work with the inclusion order of the script files? – Samuel Caillerie Dec 10 '12 at 18:18
  • I have the inclusions in the correct order. I am also trying to figure out how to add validation when I call the (AJAX) Add method. – Keith Barrows Dec 10 '12 at 18:27

1 Answers1

0

I never figured out a way to use the built in validators. What I ended up doing was this:

<asp:Content ID="myScript" ContentPlaceHolderID="pageScript" runat="server">
    <script type="text/javascript" language="javascript">
        $().ready(function () {
            $("#addItem").click(function () {
                //alert('hi');

                $.ajax({
                    url: this.href,
                    cache: false,
                    success: function (html) { $("#editorRows").append(html); }
                });
                return false;
            });

            $("a.deleteRow").live("click", function () {
                $(this).parents("div.editorRow:first").remove();
                return false;
            });
        });

        function OnDocUpload() {
            var editorRows = $('.editorRow');
            //alert(editorRows.length);
            var isGood = true;
            editorRows.each(function () {
                var input = $(this).children('.required.input').first();
                var msg = $(this).children('.display_message').first();
                //alert(input.val().length + " | " + msg.html);
                if (input.val().length < 1) {
                    isGood = false;
                    input.css('background-color', '#FEADCE');
                    msg.text("A document name is required!");
                } else {
                    input.css('background-color', '#FAFAD2');
                    msg.text("");
                }
            });
            return isGood;
        }

        function SubmitForm() {
            if (OnDocUpload()) {
                var frm = $("#LoadDocs");
                frm.submit();
                //$("#LoadDocs").submit();
            }
        }
    </script>
</asp:Content>

<asp:Content ID="Content1" ContentPlaceHolderID="MainContentPlaceHolder" runat="server">

    <h1>Create Document List</h1>

    <% 
    Html.EnableClientValidation();
    using (Html.BeginForm("CreateList", "CIPDocuments", FormMethod.Post, new { @class = "wufoo", @enctype = "multipart/form-data", @id = "LoadDocs" })) 
    { %>
        <%= Html.AntiForgeryToken() %>

        <div id="editorRows">
            <% foreach(var cipDocument in ViewData.Model.CIPDocumentAndFileList)
                   Html.RenderPartial("DocEditRow", cipDocument);
            %>
        </div>
        <br />

        <%= Html.ActionLink("Add another...", "Add", null, new { id = "addItem" }) %>

        <br />
        <br />
        <br />

        <%= Html.Button("btnSave", "Save Document List", HtmlButtonType.Button, "SubmitForm();")%>
        <%= Html.Button("btnCancel", "Cancel", HtmlButtonType.Button, "window.location.href = '" + Html.BuildUrlFromExpressionForAreas<CIPDocumentsController>(c => c.Index()) + "';") %>
    <% } %>
</asp:Content>
Keith Barrows
  • 24,802
  • 26
  • 88
  • 134