1

Let's suppose I have a form with two submit buttons: save and delete.

How can I remove/disable model validations on delete button?

3 Answers 3

3

Assuming you're using standard unobtrusive/jQuery validate; Disable client-side validation by putting a class of "cancel" on the button:

<button type="submit" class="cancel">Delete</button>

This will prevent client-side validation from firing at all in the event of this button being clicked.

For server side, just don't check if the model's valid or not.

Sign up to request clarification or add additional context in comments.

3 Comments

I am interested in client-side validation. Please describe me a little bit more your solution.
Thanks! Now I understand. I never thought it would be so simple.
@Otix Yep - this is just a convention used by jQuery Validate :)
0

For example, if you have a property Name on the model and you want NOT to validate it on delete. You first need to differentiate if the httppost is coming from the save or delete button.

Add to your Model field IsDelete.

I suggest you add in your view something like:

    @Html.HiddenFor(x => x.IsDelete)

Add onclick event to your delete button:

<button type="submit" onclick="javacript: $('#IsDelete').val('true');"> Delete </button>

In the controller do something like:

public ActionResult MyAction(MyModel model)
{
   if(model.IsDelete)
      ModelState.Remove("Name");

   var valid = ModelState.IsValid();
}

Comments

-1

You can use two separate forms in the view for the edit and delete.

Ex:

@using(Html.BeginForm("Edit", "Employee"))
{
    //Edit inputs - ex textboxes for employee details such as name, age...
    <input type="submit" value="Edit" />
} 

@using(Html.BeginForm("Delete", "Employee"))
{
    //Delete inputs - ex: hidden input for employee id
    <input type="submit" value="Delete" />
} 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.