Click here to Skip to main content
15,071,928 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi
I have a partial view with a form, when I am clicked on the submit button there is no validation error message.

This is what I have:
C#
     @using (Html.BeginForm("GetPartialView", "Manage", FormMethod.Post, new {                                                      enctype="multipart/form-data", id = "LoginForm" }))
    {
        @Html.AntiForgeryToken()
         <div class="form-group">
                        @Html.LabelFor(model => model.Isbn)
                        @Html.EditorFor(model => model.Isbn, new { htmlAttributes = new { @class = "form-control" } })
                 
  <button id="loginButton" class="btn btn-common-small" type="button">Opret</button>
}


What I have tried:

I have tried this jquey.
jQuery(document).ready(function ($) {
$('#loginButton').click(function () {

$.ajax({
type: "POST",
url: '@Url.Action("GetPartialView", "Manage")',
data: $('form').serialize(),
success: function (result) {
var form = $('#LoginForm');
if (result.redirectTo) {
window.location.href = result.redirectTo;
} else {
$("#LoginFormContainer").html(result);
form.data('validator', null);
$.validator.unobtrusive.parse(form);
}
},
error: function () {
$("#LoginForm").html(result);
}
});
});
});

But this is only work if I change the button type from submit to button, but then my fileupload wont work.

/Tina
Posted
Updated 4-May-16 9:38am
v2

1 solution

Your jQuery event handler is making an unconditional post, without validating the form first.

Try validating the form at the start of the handler:
JavaScript
$('#loginButton').click(function () {

    var $form = $('form');
    $form.validate();
    if (!$form.valid()){ return false; }
    
    ...

.validate() | jQuery Validation Plugin[^]
.valid() | jQuery Validation Plugin[^]
   
Comments
   
5ed.
I would add that if some really sensitive data should be posted, just client-side validation cannot be considered sufficient; and HTTP request bypassing JavaScript can be easily forged in no time.
—SA
ridoy 5-May-16 2:56am
   
a 5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900