Reputation: 4971
I have several input
fields of type submit
on my page. For some of these I want validation to occur as normal but on others I do not. Each submit
button posts the form back to the controller, setting a command value for each button. This allows the action to perform the relevant function. However, if I add the class cancel
to the relevant input
tag, validation doesn't occur for them. But then I don't get a value for the command posted back to the controller action. So I can either not validate or get a command value but not both.
To set up;
Models;
public void SubData
{
public int ID { get; set; }
}
public void SomeViewModel
{
public int ID { get; set; }
public List<SubData> Data { get; set; }
}
In HTML;
<input type="submit" name="command" value="AddData" />
<input type="submit" name="command" value="DeleteData/>
<input type="submit" name="command" value="SaveAll/>
Controller;
public ActionResult Index(SomeViewModel model, string command)
{
switch (command)
{
case "AddData":
model.Stuff.Add(new SubData());
break;
case "DeleteData":
// you get the idea...
break;
}
}
Javascript (taken from: https://stackoverflow.com/a/17401660);
$(function () {
// allow delete actions to trigger a submit without activating validation
$(document).on('click', 'input[type=submit].cancel', function (evt) {
// find parent form, cancel validation and submit it
// cancelSubmit just prevents jQuery validation from kicking in
$(this).closest('form').validate().cancelSubmit = true;
$(this).closest('form').submit();
return false;
});
});
So, if I have <input type="submit" class="cancel" value="AddSomething" />
then validation doesn't occur (yay!) but I get no value supplied in the action's parameter command
(boo!). Taking out cancel
triggers validation and I get a value for command
once validation is ok.
Upvotes: 0
Views: 460
Reputation: 252
Try to use evt.preventDefault()
to prevent the subimition of this input
$(function () {
// allow delete actions to trigger a submit without activating validation
$(document).on('click', 'input[type=submit].cancel', function (evt) {
//use the preventDefault() to stop any submition from here
evt.preventDefault();
// find parent form, cancel validation and submit it
// cancelSubmit just prevents jQuery validation from kicking in
$(this).closest('form').validate().cancelSubmit = true;
$(this).closest('form').submit();
return false;
});
});
Upvotes: 1