Reputation: 6151
I've got a large view model that I'm sending back to the controller - using AJAX posts. The model looks something like this:
public class FunkyThingsOrder
{
[Required]
public int id{get;set;}
[Required]
public string CustomerName{get;set;}
[Required]
public string ContactNumber{get;set;}
[Required]
public string EmailAddress{get;set;}
public List<FunkyThing>{get;set;}
public List<Freebies>{get;set;}
}
public class FunkyThing
{
[Required]
public int id{get;set;}
[Required]
public string Name{get;set;]
[Required]
public int FunkienessLevel{get;set;}
[Required]
public int QuantityOrdered{get;set;}
}
Now imagining I have a controller action
ActionResult CreateOrUpdateFunkyThingsOrder(FunkyThingsOrder orderToCreateOrUpdate)
{
}
What I'd like to be able to do is assuming the customerName, Contact Number and Email address is valid - save them off to the database - regardless of whether the funkythings are valid or not. Then iterate through the List of FunkyThings and check whether the model state for each funky thing is valid or not and if it is - save it to the database.
My question is.... is there a way I can use ModelState.IsValid to check whether each FunkyThing is indepentently valid or will I have to go through each field within the funky thing using IsValidField?
Upvotes: 1
Views: 1593
Reputation: 33853
If you want to assume in certain scenarios that part of your model is valid, regardless of whether or not it is, why not remove the validation from that property?
RemoveValidationError("FunkyThingsOrder.CustomerName");
RemoveValidationError("FunkyThingsOrder.ContactNumber");
RemoveValidationError("FunkyThingsOrder.EmailAddress");
protected void RemoveValidationError(string name)
{
for (var i = 0; i < ModelState.Keys.Count; i++)
{
if (ModelState.Keys.ElementAt(i) == name &&
ModelState.Values.ElementAt(i).Errors.Count > 0)
{
ModelState.Values.ElementAt(i).Errors.Clear();
break;
}
}
}
My question would be however, how would you save off just one field in your model if it were valid? This seems to be a difficult and clunky design. I'd rather either save off the full model or not at all.
Upvotes: 2