Dragon4ik
Member
- Joined
- Oct 24, 2020
- Messages
- 16
- Programming Experience
- Beginner
Hi. everyone!
Actually this question is the continuation of Question, but now I have the same problem on ASP.Net MVC
I have the following task : write the validation attribute, which checks, if String format is right to parse into DateTimeOffset and if it isn't, app should throw an Exception. I try to get solution from StackOverflow, but it doesn't work and I can't get why.
MyCustomAttribute code:
Model code:
Controller code:
I see that is a simple problem, but can somebody explain me why it doesn't work and how to make it to work?
Thank you for any help!!!
Actually this question is the continuation of Question, but now I have the same problem on ASP.Net MVC
I have the following task : write the validation attribute, which checks, if String format is right to parse into DateTimeOffset and if it isn't, app should throw an Exception. I try to get solution from StackOverflow, but it doesn't work and I can't get why.
MyCustomAttribute code:
C#:
public class DateStringAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
string date = value.ToString();
var format = "ddd MMM dd yyyy HH:mm:ss 'GMT'zzzz";
IFormatProvider provider = CultureInfo.InvariantCulture.DateTimeFormat;
DateTimeOffset startDate;
if (!DateTimeOffset.TryParseExact(date, format, provider, DateTimeStyles.AllowWhiteSpaces, out startDate))
{
throw new Exception("Something went wrong");
}
return ValidationResult.Success;
}
}
Model code:
C#:
public class EventModel
{
[DateString]
public string Date { get; set; }
}
Controller code:
C#:
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
EventModel eventModel = new EventModel { Date = "Fri Aug 30 2014 00:00:00 GMT+0300" };
return Content($"{eventModel.Date}");
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
I see that is a simple problem, but can somebody explain me why it doesn't work and how to make it to work?
Thank you for any help!!!