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) %>
<% 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?