0
我的ViewModel具有验证属性,以确保它不会是空的等等。 - 这是否足够,或者我应该让我的代码合同,我已经在ActionResult呢?MVC +验证属性是否足够?
例子:
// 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)
});
}
啊,感谢您的建议!但是你认为我仍然应该在ActionResult中使用我的codecontract if语句,尽管我的viewmodel中的验证属性是一样的吗? – ebb 2011-01-13 23:05:57