, , , , .
HEAD, DELETE .. RESTful (http://en.wikipedia.org/wiki/Representational_State_Transfer).
, -, javascript/ajax, javascript - jQuery. , -. , jQuery ajax. , , : , (500, 404 ..), (JSON, XML ..).
javascript - :
(function ($) {
if (!window.myWebsite) { window.myWebsite = {}; }
$.extend(myWebsite, {
get: function (url, data, callback) {
myWebsite._ajax(url, data, "GET", callback);
},
post: function (url, data, callback) {
myWebsite._ajax(url, data, "POST", callback);
},
_ajax: function (url, data, type, callback) {
$.ajax({
type: type,
url: url,
data: data,
dataType: 'json',
success: function(data, status, request) {
if( data.result == 'error' ) {
myWebsite._displayError( data.message );
}
if( $.isFunction(callback) )
callback();
},
error: function (request, status, error) {
myWebsite._displayError( error );
}
});
},
_displayError: function( text ) {
$('#errorDiv').text(error);
}
});
})(jQuery);
javascript :
myWebsite.get( '/Controller/Action', {}, function() { ... } );
javascript, ASP.NET MVC, , . javascript _ajax , JSON, "" "". MVC.
using System;
public abstract class JsonResultBase
{
#region constructors
public JsonResultBase()
: this("success", string.Empty) { }
public JsonResultBase(string result, string message)
{
if (result != "success" && string.IsNullOrEmpty(message))
{
throw new ArgumentException("message", "message must have a value when the result is not 'success'.");
}
this.result = result;
this.message = message;
}
public JsonResultBase(Exception e)
{
this.result = "error";
this.message = e.Message;
}
#endregion
#region properties
public string result { get; set; }
public string message { get; set; }
#endregion
}
, .
public class HomeController : Controller
{
private class ValuesJsonResult : JsonResultBase {
public ValuesJsonResult() : base() {}
public ValuesJsonResult(Exception e) : base(e) {}
public string[] values = new string[0];
}
public ActionResult GetList() {
try {
return Json(
new ValuesJsonResult{ values = new [] { "Sao Paulo", "Toronto", "New York" } },
JsonRequestBehavior.AllowGet
);
} catch( Exception e ) {
return Json( new ValuesJsonResult(e), JsonRequestBehavior.AllowGet );
}
}
}