5

I have a need to call a method on my controller to return a complex type using the JQuery.Ajax method.

 function CallMethodTest(Id) {
            //alert(Id);
            $.ajax({
                type: 'POST',
                url: '/MyController/MyMethod',
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                //data: "{'Id': '" + Id + "'}",
                success: function (data) {
                    alert(data);
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    alert(xhr.status);
                    alert(thrownError);
                }
            });
        }

[System.Web.Services.WebMethod]
public string MyMethod()
{
    return "ABC"; // Gives me the error on the first alert of "200" and the second alert "Syntax Error: Invalid Character"
    return "1"; // Works fine
}

As the code explains, if I return an integer (as a string) the return works and I alert "1", however, If I try and return any alpha characters I get the alerts shown in the comments of MyMethod.

5
  • 3
    Your ajax method is expecting json, this is probably the cause of the issue. Commented Sep 14, 2012 at 9:49
  • 1
    Can you add [ScriptMethod(ResponseFormat = ResponseFormat.Json)] to your WebMethod Commented Sep 14, 2012 at 9:51
  • I've added [ScriptMethod(ResponseFormat = ResponseFormat.Json)] to my webmethod, but with no luck. I'm actually wanting to return a complex type eventually so JSON will be needed for that I assume, the returning of a string was only to get the ball rolling. Commented Sep 14, 2012 at 9:59
  • Just a note, your url is /MyController/MyMethod so why are you adding the [System.Web.Services.WebMethod] code? For me I would just have public ActionResult MyMethod() and from in that I would return return Json("ABC"); Commented Sep 14, 2012 at 10:03
  • I've just seen another post where they have done that and tested it. Works brilliantly. Add that as an answer Tim and I'll accept. Thank you for your help Commented Sep 14, 2012 at 10:04

2 Answers 2

10

From your code, it looks as though you are returning the value from your Controller url: "/MyController/MyMethod"

If you are returning the value from your controller, then get rid of the [System.Web.Services.WebMethod] code and replace it with this ActionResult

[HttpPost]
public ActionResult MyMethod(){
    return Json("ABC");
}

Also, if you are ever going to call a method in your controller via GET then use

public ActionResult MyMethod(){
    return Json("ABC", JsonRequestBehavior.AllowGet);
}
Sign up to request clarification or add additional context in comments.

Comments

2

In View You use the following code,

  function ItemCapacity() {

        $.ajax({
            type: "POST",
            url: '@Url.Action("ItemCapacityList", "SalesDept")',
            data: { 'itemCategoryId': itemCategoryIds },
            dataType: 'json',
            cache: false,
            success: function (data) {

                var capacityCounter = 0;
                var capacitySelected = "";

                for (var i = 0; i < rowsCount; i++) {

                    var tr = $("#gvSpareSetItemsDetails tbody tr:eq(" + i + ")");
                    var categoryId = $(tr).find('td:eq(5)').text();
                    var isSelectOrNot = $(tr).find('td:eq(1)').find('select');

                    if (isSelectOrNot.is('select')) {

                        $.map(data, function (item) {
                            if (categoryId == item.ItemCategoryID) {
                                isSelectOrNot.get(0).options[isSelectOrNot.get(0).options.length] = new Option(item.CapacityDescription, item.ItemCapacityID);
                                capacityCounter = capacityCounter + 1;
                                capacitySelected = item.ItemCapacityID;
                            }
                        });

                        if (capacityCounter == 1) {
                            isSelectOrNot.val(capacitySelected);
                        }

                        capacityCounter = 0;
                        capacitySelected = "";
                    }
                }
            },
            error: function () { alert("Connection Failed. Please Try Again"); }
        });
    }
}

In the Controller Use the following Code,

    public JsonResult ItemCapacityList(string itemCategoryId)
    {
        List<ItemCapacity> lsItemCapacity = new List<ItemCapacity>();

        string[] itemCategory = itemCategoryId.Split('#');

        int itemCategoryLength = itemCategory.Length, rowCount = 0;
        string itemCategoryIds = string.Empty;

        for (rowCount = 0; rowCount < itemCategoryLength; rowCount++)
        {
            itemCategoryIds += "'" + itemCategory[rowCount].Trim() + "',";
        }

        itemCategoryIds = itemCategoryIds.Remove(itemCategoryIds.Length - 1);

        lsItemCapacity = salesDal.ReadItemCapacityByCategoryId(itemCategoryIds);

        return new JsonResult { Data = lsItemCapacity };
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.