MVC + Is validation attributes enough?
Posted
by
ebb
on Stack Overflow
See other posts from Stack Overflow
or by ebb
Published on 2011-01-13T22:24:59Z
Indexed on
2011/01/13
22:53 UTC
Read the original article
Hit count: 201
My ViewModel has validation attributes that ensure that it wont be empty etc. - Is that enough or should I let my the code contracts I have made be in the ActionResult too?
Example:
// CreateCaseViewModel.cs
public class CreateCaseViewModel
{
[Required]
public string Topic { get; set; }
[Required]
public string Message { get; set; }
}
// CaseController.cs
[AuthWhere(AuthorizeRole.Developer)]
[HttpPost]
public ActionResult Create(CreateCaseViewModel model)
{
if(!ModelState.IsValid)
{
// TODO: some cool stuff?
}
if (string.IsNullOrWhiteSpace(model.Message))
{
throw new ArgumentException("Message cannot be null or empty", model.Message);
}
if (string.IsNullOrWhiteSpace(model.Topic))
{
throw new ArgumentException("Topic cannot be null or empty", model.Topic);
}
var success = false;
string message;
var userId = new Guid(_membershipService.GetUserByUserName(User.Identity.Name).ProviderUserKey.ToString());
if(userId == Guid.Empty)
{
throw new ArgumentException("UserId cannot be empty");
}
Case createCase = _caseService.CreateCase(model.Topic, model.Message);
if(createCase == null)
{
throw new ArgumentException("Case cannot be null");
}
if(_caseService.AddCase(createCase, userId))
{
message = ControllerResources.CaseCreateFail;
}
else
{
success = true;
message = ControllerResources.CaseCreateSuccess;
}
return Json(new
{
Success = success,
Message = message,
Partial = RenderPartialViewToString(ListView, GetCases)
});
}
© Stack Overflow or respective owner