我想要的东西比Jarrett建议的要多一些,所以这就是我要做的:
JsonDataContractActionResult:
public class JsonDataContractActionResult : ActionResult{ public JsonDataContractActionResult(Object data) { this.Data = data; } public Object Data { get; private set; } public override void ExecuteResult(ControllerContext context) { var serializer = new DataContractJsonSerializer(this.Data.GetType()); String output = String.Empty; using (var ms = new MemoryStream()) { serializer.WriteObject(ms, this.Data); output = Encoding.Default.GetString(ms.ToArray()); } context.HttpContext.Response.ContentType = "application/json"; context.HttpContext.Response.Write(output); }}JsonContract()方法,添加到我的基本控制器类中:
public ActionResult JsonContract(Object data) { return new JsonDataContractActionResult(data); }用法示例:
public ActionResult Update(String id, [Bind(Exclude="Id")] Advertiser advertiser) { Int32 advertiserId; if (Int32.TryParse(id, out advertiserId)) { // update } else { // insert } return JsonContract(advertiser); }Note: If you’re looking for something more performant than
JsonDataContractSerializer, you can do the same thing using JSON.NET instead.
While JSON.NET doesn’t appear to utilize DataMemberAttribute, it does have its
own JsonPropertyAttribute which can be used to accomplish the same thing.



