Reputation:
I,ve been working on a MVC C# project and I need to send the info (model) from my View to the due controller action but after managing some validations via jQuery and the click event of the submit button, here is the javascript code on click of submit button and its validation (works fine)
$("#sentInfo").click(function (e) {
e.preventDefault();
$("#idProveedor").val(proveedor);
$("#idacme").val('ingresar');
var table = $('#myTable');
table.find('tbody tr').each(function (index, tr) {
if ($(tr).find("td:eq(2)").html() === $("#idDUI").val()) {
alert('ya existe el DUI');
exit;
}
else if ($(tr).find("td:eq(3)").html() === $("#idISSS").val()) {
alert('ya existe el ISSS');
exit;
}
else {
$("form").submit();
}
});
});
the code above sets the values to the #idProveedor and #idacme inputs and also validate if the DUI or ISSS already exists but if the values already exist it always send the model to the action and what I want that if ISSS or DUI values exists then the model shouldn't be send to the action method. Can anyone help me?
this is my form code
@using (Html.BeginForm("EnviarEALG", "Home", FormMethod.Post, new { @class = "form-horizontal", role = "form", id = "FormEmp" }))
{
...
some code goes here
...
<input type="submit" value="Ingresar Empleado" class="btn btn-info" id="sentInfo" />
}
this is the code with modifications:
$("#sentInfo").click(function (e) {
e.preventDefault();
$("#idProveedor").val(proveedor);
$("#idacme").val('ingresar');
var table = $('#myTable');
table.find('tbody tr').each(function (index, tr) {
if ($(tr).find("td:eq(2)").html() === $("#idDUI").val()) {
alert('ya existe el DUI');
exit;
}
else if ($(tr).find("td:eq(3)").html() === $("#idISSS").val()) {
alert('ya existe el ISSS');
exit;
}
else {
$("FormEmp").submit();
}
});
});
and the button
<input type="button" value="Ingresar Empleado" class="btn btn-info" id="sentInfo" />
Upvotes: 1
Views: 2434
Reputation: 2012
One solution is to use ajax to send your data from your view to your controller. I use this often and might be a good solution for you since you are using a jQuery click event. Below is an untested example but it will give you an idea of how to do it.
function Save(model){
var data = {
'modelNameToPass': model
}
$.ajax({
url: "/Home/EnviarEALG", // "/ControllerName/Method"
data: data,
type: "POST",
success: function(response){
//code to do something on success
},
error: function(response){
//do error stuff here
}
});
}
Then your controller should already be set up like this..
[HttpPost]
public ActionResult EnviarEALG(DataModel modelNameToPass)
{
}
Hopefully this helps!
Upvotes: 1