JQuery.Ajax和MVC4

时间:2012-09-14 09:40:43

标签: c# asp.net-mvc jquery

我需要在我的控制器上调用一个方法来使用JQuery.Ajax方法返回一个复杂类型。

 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
}

正如代码所解释的,如果我返回一个整数(作为字符串),则返回有效并且我提醒“1”,但是,如果我尝试返回任何字母字符,我会收到MyMethod注释中显示的警报。 / p>

2 个答案:

答案 0 :(得分:10)

从您的代码中看起来好像是从Controller url: "/MyController/MyMethod"

返回值

如果要从控制器返回值,请删除[System.Web.Services.WebMethod]代码并将其替换为ActionResult

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

此外,如果您要通过GET在控制器中调用方法,请使用

public ActionResult MyMethod(){
    return Json("ABC", JsonRequestBehavior.AllowGet);
}

答案 1 :(得分:2)

在视图中您可以使用以下代码

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

在控制器中使用以下代码,

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