开发者

MVC + Is validation attributes enough?

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 (stri开发者_开发技巧ng.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)
    });
}


Your code does not make a lot of sense to me.

  • throw new ArgumentException will return error 500 (server error). You had better follow REST principles and send back appropriate error code (e.g. 402 bad request with appropriate description of the error) or return your JSON with success=false and appropriate error message.

  • Your code seems to follow even if Model is not valid. Fork must include if valid -> save, otherwise send errors to client.

  • You do not seem to be using model error messages. They are useful and you can find them in ModelState.

You fix these issues and I think you have a nice code there.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜