views:

33

answers:

1

Hey,

I'm trying to call a server-side action in a controller from jQuery:

$.ajax({
            url:'http://localhost:88/admin/business/11/GetChildBusinessTypes',
            data: { parentId: $('#business_parentbusinesstype_id').val() },
            dataType: 'json',
            success: fillChildBusinessTypes,
            error: ajaxError
        });

Here is the controller action:

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);
        }

It's giving me this error:

MonoRail could not resolve a view engine instance for the template 'admin\business\GetChildBusinessTypes' There are two possible reasons: either the template does not exist, or the view engine that handles an specific file extension has not been configured correctly web.config (section monorail, node viewEngines).

It's clear it's trying to get the action as if it were a view and erroring out. I tried sending it as a POST instead of a GET but receive the same rror. What do I need to do to get this to work?

Thanks! Justin

+1  A: 

Here's the answer for others who are looking to call controller actions from jQuery and return JSON...

Controller Method:

[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'));
    }
Justin