我正在尝试从jQuery调用控制器中的服务器端操作:
$.ajax({
url:'http://localhost:88/admin/business/11/GetChildBusinessTypes',
data: { parentId: $('#business_parentbusinesstype_id').val() },
dataType: 'json',
success: fillChildBusinessTypes,
error: ajaxError
});
以下是控制器操作:
public string GetChildBusinessTypes(int parentId)
{
//get child business types.
var businessTypes = BusinessTypeRepository.GetChildBusinessTypes(parentId);
//convert to JSON.
var serializer = new JavaScriptSerializer();
return serializer.Serialize(businessTypes);
}
它给了我这个错误:
MonoRail无法解析模板'admin \ business \ GetChildBusinessTypes'的视图引擎实例有两个可能的原因:模板不存在,或者处理特定文件扩展名的视图引擎尚未正确配置了web.config(monorail节,节点viewEngines)。
很明显,它正在尝试将操作视为一个视图并且错误输出。我尝试将其作为POST而不是GET发送,但收到相同的错误。我需要做些什么才能让它发挥作用?
谢谢! 贾斯汀
答案 0 :(得分:1)
对于那些希望从jQuery调用控制器操作并返回JSON ...
的人来说,这是答案控制器方法:
[return: JSONReturnBinder(Properties = "Id,Name")]
public BusinessType[] GetChildBusinessTypes(int parentId)
{
var businessTypes = BusinessTypeRepository.GetChildBusinessTypes(parentId);
return businessTypes;
}
使用Javascript:
$(document).ready(function () {
$('#business_parentbusinesstype_id').change(function () {
jQuery.ajax({
url: "$UrlHelper.For("%{action='$business.site.id/GetChildBusinessTypes'}")",
data: { parentId: $('#business_parentbusinesstype_id').val() },
dataType: 'json',
type: 'GET',
success: fillChildBusinessTypes,
error: ajaxError
});
});
});
function fillChildBusinessTypes(json) {
//get business types.
var businessTypes = eval(json);
//bind business types to dropdown.
$("#business_businesstype_id").get(0).options.length = 0;
$("#business_businesstype_id").get(0).options[0] = new Option("Select a Business Type", "0");
jQuery.each(businessTypes, function(index, item) {
$('#business_businesstype_id').get(0).options[$("#business_businesstype_id").get(0).options.length] = new Option(item.Name, item.Id);
});
//show child dropdown.
Show($('#spnChildBusinessTypes'));
}