以下是 IService1 中的 OperationContract :
[OperationContract]
[WebGet(UriTemplate = "/GetStates",ResponseFormat = WebMessageFormat.Json)]
List<string> GetStates();
Implementation of method GetStates in Service1 class :
public List<string> GetStates()
{
DB_MVCEntities db = new DB_MVCEntities();
// string temp = CountryName.Country;
string temp = "india";
var CountryId = (from n in db.tblCountries
where n.Country == temp
select new { n.Cid }).Single();
int ii = CountryId.Cid;
// int ii = (ObjectQuery<Int32>)CountryId;
// object oo = CountryId;
//int countryId = Convert.ToInt32(CountryId);
var StateResult = (from n in db.tblStates
where n.Cid == CountryId.Cid
select n.StateName).ToList();
List<string> aaa = new List<string>();
foreach (object o in StateResult)
{
string t = o.ToString();
aaa.Add(o.ToString());
}
return aaa;
}
在上述方法中,我使用实体框架从数据库中获取状态列表。当我在浏览器上执行 wcf 服务时,它工作正常。意味着我得到以下输出
上述服务的输出如下:
["MH","AP"]
Code for consuming it in MVC3, Register.csheml file:
$(document).ready(function () {
$("#Country").change(function () {
$.ajax({
url: 'http://localhost:1264/Service1.svc/GetStates',
type: 'GET',
contentType: 'application/json; charset=utf-8',
success: function (data) {
$('#State option').remove();
$.each(data, function (index, val) {
var optionTag = $('<option></option>');
$(optionTag).text(val.toString());
$('#State').append(optionTag);
});
},
error: function () {
alert("bye..countryes.");
}
});
});
});
当 Country 发生 Change 事件时,我得到以下输出: control is not going in Success 方法。
成功后,我将状态列表绑定到状态下拉列表。
但我无法在 mvc3 中获取 json 数据。
bye..countryes.
What was the error?
Thanks in advance.