I have an example application trying to learn jQuery validation and submit a form in this scenerio.
There is one text box on the page (EnvelopeID for each class envelope). If the submit button is pressed and the text field is empty, then I want to show an error message. If it is not empty, I want to send an ajax request to GetData Action. The action returns partial views (value 1 or 2) or an error string.
Problem:
- Customer verification does not occur here.
- How can I get
$(form).submit to stick to jquery validation and not post data if it's empty? I can verify that the text field is empty or not before publication (manually), but I want to use the correct path.
This same example works with MSAjax and validation without any problems.
Head of Home
<script type="text/javascript" src="<%= Url.Content("~/Scripts/jquery-1.4.1.min.js") %>"></script> <script type="text/javascript" src="<%= Url.Content("~/Scripts/jquery.validate.min.js") %>"></script> <script type="text/javascript" src="<%= Url.Content("~/Scripts/MicrosoftMvcJQueryValidation.js") %>"></script>
Grade:
namespace PartialViews.Models { public class Envelope { [Required(ErrorMessage="Envelope ID is required!")] public string EnvelopeID { get; set; } } }
Data Action:
[HttpPost] public ActionResult GetData(Envelope envelope) { ActionResult result = null; if (ModelState.IsValid) { Information myInfo = newInformation(); if (envelope.EnvelopeID == "1") { result = View("TQ1PV", myInfo); //partial view } elseif (envelope.EnvelopeID == "2") { result = View("TQ2PV", myInfo); //partial view } else { result = Content("Error"); } } else { result = View("index", envelope); } return result; }
Index Action:
public Action Result Index() { return View(); }
JS on View - Index
<script type="text/javascript"> $(function () { //onload $("#evid").focus(); $("form[name='EVIDForm']").submit(function () { var action = $(this).attr('action'); var evid = $("#evid").val(); var tdata = $(this).serialize(); alert(tdata); $message = $("#resultDiv"); $message.html('').removeClass("red"); $.ajax({ cache: false, type: "post", url: action, data: tdata, dataType: "html", error: function (xhr, ajaxOptions, thrownError){ alert('system error'); }, success: function(data){ if (data == 'Error') $message.html("No such EV ID found!").addClass("red"); else $message.html(data); } }); return false; }); }); </script>
HTML to view - index:
<% Html.EnableClientValidation(); %> <%= Html.ValidationSummary() %> <% using (Html.BeginForm("GetData", "Info", FormMethod.Post, new {name = "EVIDForm" })) {%> <%= Html.LabelFor(model => model.EnvelopeID) %> <%= Html.TextBoxFor(model => model.EnvelopeID, new { maxlength = "8"})%> <%= Html.ValidationMessageFor(model => model.EnvelopeID,"*") %> <br /><br /> Correct EVIDs are 1 and 2. All other entries will result in an error. <br /><br /> <input type="submit" value="submit" /> <%} %> <div id="resultDiv" style="margin-top: 20px;"></div>
thanks