Joh*_*ohn 2 c# ajax json entity-framework web-services
我的JSON作为转义字符串返回,我想要没有反斜杠和外引号的对象.我确定我错过了一个演员或简单的东西,但我会把完整的代码放在这里以避免误解.
我正在尝试通过ajax/JSON/asmx Web服务将一些数据导入Infragistics Ignite UI网格.我有数据回来了,但格式不正确.我不确定问题是在我的ajax js或c#方法返回类型(字符串)还是JSON序列化?
这是我如何使用jquery ajax调用来调用Web服务:
var jqxhr = $.ajax(
{
type: 'POST',
contentType: "application/json; charset=utf-8",
url: "/WebMethods/AssetWebService.asmx/GetAssets",
dataType: "json",
success: success,
error: function (xhr, msg) { alert(msg + '\n' + xhr.responseText); }
});
function success(msg) {
var entityColumns = getColumns();
var entityData = msg.d;
gridSetup(entityData, entityColumns);
}
function gridSetup(entityData, entityColumns) {
$("#assetGrid").igGrid(
{
autoGenerateColumns: false,
autoGenerateLayouts: false,
dataSource: entityData,
columns: entityColumns
}
);
}
Run Code Online (Sandbox Code Playgroud)
Webservice c#代码从实体框架获取对象:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class AssetWebService : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetAssets()
{
List<Asset> Assets = new List<Asset>();
using (var db = new CognyxMES())
{
Assets = db.Assets.ToList();
}
var results = from a
in Assets
select new
{
Id = a.Id,
Name = a.Name,
AssetTypeId = a.AssetTypeId
};
return results;
}
}
Run Code Online (Sandbox Code Playgroud)
当我在VS2013中调试时(我的网格不显示任何数据),我收到的JSON看起来像这样:
"[{\"Id\":3,\"Name\":\"My Asset\",\"AssetTypeId\":1}]"
Run Code Online (Sandbox Code Playgroud)
我希望它看起来像这样,因为当我硬编码时我的网格工作:
[{ "Id": 3, "Name": "My Asset", "AssetTypeId": 1 }]
Run Code Online (Sandbox Code Playgroud)
我是c#的新手JSON,所以我知道我可以使用字符串替换或类似的方法将其破解到位,但我正在寻找一个更优雅的修复和解释我所缺少的东西.谢谢
你要返回的IS
是一个字符串而不是JSON
.那是你的问题.
你的方法应该是这样的.ASP.NET为您处理剩下的事情.
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public IEnumerable<object> GetAssets()
{
using (var db = new assetEntities())
{
var results = from a
in db.Assets
select new
{
Id = a.Id,
Name = a.Name,
AssetTypeId = a.AssetTypeId
};
return results;
}
}
Run Code Online (Sandbox Code Playgroud)
Based on your jQuery request you have specified that you want JSON and your
ResponseFormat = ResponseFormat.Jsonreturned`强制执行此操作...因此您的Web服务将为您序列化对JSON的响应.十分简单.无需手动序列化.
归档时间: |
|
查看次数: |
3654 次 |
最近记录: |