0

I have a model like belowe:

 public class AddPurchaseViewModel
{
    [Required(ErrorMessage="Please enter ...")]
    public string InvoiceNumber { get; set; }

    [Required(ErrorMessage="Please enter ...")]
    public DateTime InvoiceDate { get; set; }

    [Required(ErrorMessage="Please enter ...")]
    public Guid BusinessPartnerId { get; set; 

}

and in View I have two Submit button Like this :

<button type="submit" class="btn btn-success" name="command" value="save">Save</button>
<button type="submit" class="btn btn-warning" name="command" value="SaveAsTemp" >Save And Temp</button></li>

and in controller I have :

 public virtual ActionResult Create(AddPurchaseViewModel purchaseViewModel, string command)
    {
        if (!ModelState.IsValid)
            return View(purchaseViewModel);
        var result = AddPurchaseStatus.AddFailed;
        if (command.ToLowerWithTrim()== "Save".ToLowerWithTrim())
            result = _purchaseService.Add(purchaseViewModel);
        else
            result = _purchaseService.AddAsTemp(purchaseViewModel);
        return View();
    }

I want when User clicked On Submit button Save ,user Should Fill All textboxes in this case ,ModelState handel it and works fine .

but when clicked on SaveAsTemp in this case dont Required BusinessPartner to fill .

I dont want Check one by one with If because my model has mor than 20 fields . Is there a way to do this ?

tereško
  • 58,060
  • 25
  • 98
  • 150
Uthman Rahimi
  • 708
  • 5
  • 22
  • **This will help you definetly** [How to put conditional Required Attribute into class property to work with WEB API?](http://stackoverflow.com/questions/20642328/how-to-put-conditional-required-attribute-into-class-property-to-work-with-web-a) – CodeConstruct Mar 08 '16 at 12:55

2 Answers2

0

You can disable the validation on clicking the SaveAsTemp button using JQuery

$('input[type="button"][value="SaveAsTemp "]').click(function() {
    var settngs = $.data($('#MyForm'), 'validator').settings;
    settngs.ignore = ".ignore";
});

Substitute #MyForm with your form Id

Or for an Individual field

$("#SomeValue").removeAttr("data-val-required");

Assuming that it its a 'Required' validator

In your controller you can disable/clear errors on specific fileds as follows

ModelState["MyField"].Errors.Clear();
James Dev
  • 2,979
  • 1
  • 11
  • 16
0

Please check conditional validation http://www.codeproject.com/Articles/541244/Conditional-ASP-NET-MVC-Validation-using-Data-Anno Hope it helped.

joint_ops
  • 312
  • 1
  • 5
  • 20