开发者

jquery, c#, server validation and validation blocks

Im using the ms validation blocks to validate user input posted using jquery (ajax). Can someone give me an example of the best way to inform the user that the data does not validate.

Do i simply throw an exception and use the error event of the $.ajax function to inform the user of the issues or is there a better way 开发者_Python百科of handling this?

thanks in advance


If you're using MVC, there's a good example of using the built in data annotations logic with jquery here: http://geekswithblogs.net/stun/archive/2011/01/28/aspnet-mvc-3-client-side-validation-summary-with-jquery-validation-unobtrusive-javascript.aspx

If you're going to be doing some error handling above and beyond basic validation on the server, then personally I use the error event to handle critical errors (invalid permissions, server errror, etc..) and then do my validation/error checking in the success. If you do a lot of ajax parsing, then making simple custom json result object is somtimes handy:

$.ajax(..
  success : function(item) { 
    if( !item.ok ) { /* handle validation logic*/ } 
    else { /* success */ }
  }
);

Where your json return object could look like this

public class JsonResultObject
{
  public bool ok { get; set; }
  public string message { get; set; }
  public object data { get; set; }
}

Then in your controller (if MVC) you return it as follows:

public JsonResult Validate( CustomPostModel model )
{
    JsonResultObject result = new JsonResultObject()
    {
      ok = false,
      message = "Some custom error message here",
      data = model
    }
    return Json(result);
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜