我在调用 Web 服务并将 Json 结果返回到视图的 asp.net mvc Web 应用程序中有以下操作方法:-
public ActionResult ListPackages()
{
using (var client = new WebClient())
{
try{
var query = HttpUtility.ParseQueryString(string.Empty);
UriBuilder("http://localhost:8080/jw/web/json/workflow/package/list");
url.Query = query.ToString();
string json = client.DownloadString(url.ToString());
Thread.Sleep(500);
return Content(json, "application/json");
}
catch (System.Net.WebException ex) {
return Content("Error, service is down. please try again later", "application/json");
}
}
}
然后在视图上我定义了以下 Ajax.Actionlink:-
@Ajax.ActionLink("Get Process List", "ListPackages", "Home",
new AjaxOptions
{
HttpMethod = "GET",
LoadingElementId = "tobehide",
OnSuccess = "getpackagelist"
})
和以下 getpackagelist java 脚本:-
function getpackagelist(result) {
$('#products').empty();
$('#title').text("All Processes");
$.each(result.data, function (key, val) {
var str = val.packageName;
$('<li/>', { text: str }).appendTo($('#products'));
});
$('#tobehide').hide();
}
我面临的问题是,如果 Web 服务关闭并且System.Net.WebException
引发异常,则" Error, service is down. please try again later "
maeeage 将不会显示在视图中,并且在 ajax 加载图像后不会显示任何内容......
:::编辑:::
我将脚本修改为:-
function getpackagelist(result) {
if (result.error == null) {
$('#products').empty();
$('#title').text("All Processes");
$.each(result.data, function (key, val) {
var str = val.packageName;
$('<li/>', { text: str })
.appendTo($('#products'));
});
$('#tobehide').hide();
}
else {
$('<li/>', { text: result.error })
.appendTo($('#products'));
}
动作方法如下:-
catch (System.Net.WebException) {
return new JsonResult()
{
Data = new { error = "Error, service is down. please try again later" }
};
但如果引发 WebExsception,仍然不会显示错误。BR