Is it possible to generate computed values for properties when using Data Annotation Validation in ASP.NET MVC (3)?
As the title says, is it possible to generate computed values for properties when using Data Annotation Validation in ASP.NET MVC (3)?
Consider a credit card example. The credit card must have an expiration date, usually of Month and Year. In the user interface it's generally best to have select
fields for the user to pick from instead of text
fields. On the other side however when sending the data to a payment gateway, it's usually one string in multiple formats: M/Y
; MM/YY
; MM/YYYY
; etc.
So what I want to accomplish is to generate the final string after I've validated the two individual dates.
Anyway, it would be awesome if someone can point me in the right direction. I've only used the built in attributes, so I guess treat me as a nubski when it come开发者_运维知识库s to something custom like this.
Assuming you have Month and Year properties:
[Range(1, 12)]
public int Month { get; set; }
[Range(2011, 2100)]
public int Year { get; set; }
you could have a third property on your view model which represents the required value:
public string ExpirationDate
{
get
{
return new DateTime(Year, Month, 1).ToString("MM/yyyy");
}
}
So, once your view model has successfully passed validation you could send the ExpirationDate property to the payment gateway:
[HttpPost]
public ActionResult Pay(PayViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
PaymentGateway.Pay(model.CCNumber, model.ExpirationDate);
return RedirectToAction("Success");
}
Add a property that doesnt show in the GUI, and concatenates your values:
class CreditCard
{
public string ExpirationYear { get; set; }
public string ExpirationMonth { get; set; }
public string ExpirationDate
{
get
{
return string.Format("{0}/{1}", ExpirationMonth, ExpirationYear);
}
}
}
Or you could use a method in which you supply the format
精彩评论