EricGS
EricGS

Reputation: 1333

validate form on MVC4 but avoid submit

i have a set of fields on a view on my aplication, i need to validate those fields before refreshing a jqgrid, but i need to prevent the submit functiuon to post to the server, i only need the form to validate the fields and then call a jquery funcition. but i dont know how to do it.

until now i have somthing like:

@using (Html.BeginForm())
{
   @Html.AntiForgeryToken()
   @Html.ValidationSummary(true)

   @Html.HiddenFor(m => m.scheduledIdPersonaSeleccionada)
   @Html.ValidationMessageFor(model => model.scheduledIdPersonaSeleccionada)

   <button type="submit" class="BTNTexto" id="buscarPorPersona">
         <img src="~/Images/Icons/search.png" />
         <span>@Html.Raw(Res_String.BuscarTurnos)</span>
   </button>
}

and a jquery function called reloadGrid(), so i need that when i press the button the validation cheks the fields (1 on my example) then if all is ok call my reloadGrid() function, also my validation is not working

pd jquery validation libraries are loaded ok

Upvotes: 0

Views: 952

Answers (1)

Matt Bodily
Matt Bodily

Reputation: 6423

there are 3 ways that we use. First use @Rosdi's code and add your validation to the event

if($('#scheduledIdPersonaSeleccionada').val() == ""){
    alert('something');
}

you can also use an ajax call back to the server and send the fields that you want to validate

$.ajax({
    type: "POST",
    url: "@(Url.Action("Action", "Controller"))",
    data: { data: 'data', data1: 'data1'},
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (result) {
        if(result.Success){

        }else{

        }
    }
});

you mentioned avoiding submit but we also use that. Put an attribute on the field

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

and then in your controller check model state

if(ModelState.IsValid){

}else{
    return View(model);
}

the third way is the easiest since it sends the model back for you and the checking is done with the attributes you have sent. Hopefully this helps.

Upvotes: 1

Related Questions