我在我的asp.net控制器上使用下面的代码在javascript上返回我的Ajax上的Json对象
public JsonResult myMethod() { // return a Json Object,you could define a new class return Json(new { Success = true,//error Message = "Success" //return exception }); }
jQuery的阿贾克斯:
$.ajax({ type: "POST",url: url_,data: search,success: function(data) { //Show Json Properties from Controller ( If Success == false show exception Message from controller ) if (data.Success) { alert(data.Message); //display success } else { alert(data.Message) //display exception } },error: function(XMLHttpRequest,textStatus,errorThrown) { alert("error: " + XMLHttpRequest.responseText); },dataType: 'json' });
如何在Web Api控制器上完成?
你能给我一些例子或网址作为参考。
感谢致敬
解决方法
如果你自己创建一个新的HttpContent类来提供JSON,比如……
public class JsonContent : HttpContent { private readonly MemoryStream _Stream = new MemoryStream(); public JsonContent(object value) { Headers.ContentType = new MediaTypeHeaderValue("application/json"); var jw = new JsonTextWriter( new StreamWriter(_Stream)); jw.Formatting = Formatting.Indented; var serializer = new JsonSerializer(); serializer.Serialize(jw,value); jw.Flush(); _Stream.Position = 0; } protected override Task SerializeToStreamAsync(Stream stream,TransportContext context) { return _Stream.CopyToAsync(stream); } protected override bool TryComputeLength(out long length) { length = _Stream.Length; return true; } }
那你可以做到,
public HttpResponseMessage Get() { return new HttpResponseMessage() { Content = new JsonContent(new { Success = true,//error Message = "Success" //return exception }) }; }
就像你对JsonResult一样。