Вопрос

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

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

Это было полезно?

Решение

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.

Другие советы

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();
}

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" />
} 
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top