asp.net mvc 3 - Validation attributed is cached -
i have next code in custom validation attribute called daterange:
private datetime _mindate = datetime.today.addyears(-100); private datetime _maxdate = datetime.maxvalue; // string representation of min date (yyyy/mm/dd) public string min { { homecoming formatdate(_mindate, datetime.today.addyears(-100)); } set { _mindate = value == "today" ? datetime.today : parsedate(value, datetime.today.addyears(-100)); } } // string representation of max date (yyyy/mm/dd) public string max { { homecoming formatdate(_maxdate, datetime.maxvalue); } set { _maxdate = value == "today" ? datetime.today : parsedate(value, datetime.maxvalue); } }
then write attribute in metadata on property of entity model this:
[daterange(max = "today")] public string somedateproperty { get; set; };
i set breakpoint on max property's getter. first time open view, breakpoint activated , datetime.today got. consequent refresh of view not activate breakpoint , old value got. think it's caching validation attribute. question is: because of caching? if is, how disable it? in advance
the constructor custom attributes nail once, no thought how turn off sort of caching. way got round scenario, deal date calculation in "isvalid" method.
i created date in past attribute, needed date in past, set how long in past valid.
public class dateinpastattribute : validationattribute { private const string defaulterrormessage = "'{0}' must in past."; public int daysinpastallowed { get; set; } public dateinpastattribute(int daysinpastallowed) : base(defaulterrormessage) { this.daysinpastallowed = daysinpastallowed; } public override bool isvalid(object value) { if (!(value datetime)) { homecoming true; } datetime maxdate = datetime.now; datetime mindate = maxdate.adddays(this.daysinpastallowed * -1); datetime datevalue = (datetime)value; homecoming mindate <= datevalue && datevalue <= maxdate; } public override string formaterrormessage(string name) { homecoming string.format(cultureinfo.currentculture, this.errormessagestring, name); } }
you can utilize in view model this:
[dateinpast(365)] public datetime datereceived { get; set; }
which allow date entered within lastly year. amend scenario require.
asp.net-mvc-3 validation custom-attributes
No comments:
Post a Comment