C#将控制器数据返回到JSONP输出以进行自动完成

时间:2016-03-13 20:26:46

标签: c# asp.net-mvc autocomplete jsonp

我在C#MVC中向JSONP输出控制器数据时遇到了一些麻烦,以便与JQuery自动完成一起使用。我想做的就是获取2个参数,以及JSONP的回调工作,查询返回基于搜索的匹配课程标题。

CourseController.cs

    public JsonResult GetPredictiveCourseTitleSearchResults()
    {
        var jsonbuilder = "";
        var q = HttpContext.Request.Params["q"];
        var year = HttpContext.Request.Params["year"];
        var callback = HttpContext.Request.Params["callback"];
        var model = new courseModel
        {
            SearchList = GetCourses(q,year)
        };
        var results = model.SearchList.Items.ToList();
        int count = results.Count();
        int resultCount = 0;

        if (callback != "")
        {
            jsonbuilder += callback + "(";
        }
        jsonbuilder += "[";
        foreach(var result in results)
        {

            if(resultCount+1 == count)
            {
                jsonbuilder += "{\"title\":" + "\"" + result.Fields["title"].ToString() + "\"}";
            }
            else
            {
                jsonbuilder += "{\"title\":" + "\"" + result.Fields["title"].ToString() + "\"},";
            }

            resultCount++;
        }
        jsonbuilder += "]";
        if (callback != "")
        {
            jsonbuilder += ")";
        }
        return Json(jsonbuilder, JsonRequestBehavior.AllowGet);
    }

CourseModel.cs

public class courseModel
{
    public ListModel<Item> SearchList { get; set; }
    public string title { get; set; }

}

App.js

 $("#course_search_input")
     .bind("keydown", function (event) {
         if (event.keyCode === $.ui.keyCode.TAB &&
             $(this).autocomplete("instance").menu.active) {
             event.preventDefault();
         }
     })
    .autocomplete({
        source: function( request, response ) {
            $.ajax({
                url: "http://leedsbeckett/search/getpredictivecoursetitlesearchresults/",
                dataType: "jsonp",
                type: "POST",
                data: {
                    q: request.q,
                    year: $("#selectedyear").val()
                },
                success: function (data) {
                    response( $.map( data.stuff, function ( item ) {
                        return {
                            label: item.title,
                            value: item.title
                        };
                    }));
                },
                error: function (XHR, textStatus, errorThrown, data) {

                    alert("Data"+data);
                    alert("XHR error: " + XHR);
                    alert("error: " + textStatus);
                    alert("error: " + errorThrown);
                }
            });
        },
        minLength: 3,
        select: function( event, ui ) {
            log( ui.item ?
              "Selected: " + ui.item.label :
              "Nothing selected, input was " + this.value);
        },
        open: function() {
            $( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
        },
        close: function() {
            $( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
        }

输出JSON文件

"jQuery1111023084966000169516_1457628798511([{\"title\":\"Course title example\"}])"

然而,这并没有被加载,它只是JQuery中的错误,数据未知。

我也尝试过:

JavaScriptSerializer js = new JavaScriptSerializer();
        CourseJSON [] courses = js.Deserialize<CourseJSON[]>(jsonbuilder);
return Json(courses, JsonRequestBehavior.AllowGet);

但是由于它没有识别回调前缀而导致错误。

任何帮助都会非常感激,因为我不知道我哪里出错了!

谢谢,

安迪

2 个答案:

答案 0 :(得分:0)

您必须设置正确的内容类型。它应该是$ .ajax调用中的application/Javascript

Best content type to serve JSONP?

url: "http://leedsbeckett/search/getpredictivecoursetitlesearchresults/",
            dataType: "jsonp",
            type: "POST", **jsonp:"callback"**,

答案 1 :(得分:0)

我发现了为什么JSONP没有从C#正确返回的问题

我有jsonresult返回json,它需要是actionresult,返回contenttype,在这里搜索后发现:Can I convert a JSON string into JsonResult?

添加contenttype然后将字符串转换为真正的JSON,JS可以读取:

public ActionResult GetPredictiveCourseTitleSearchResults()
    {
        var jsonbuilder = "";
        var q = HttpContext.Request.Params["q"];
        var year = HttpContext.Request.Params["year"];
        var callback = HttpContext.Request.Params["callback"];
        var model = new courseModel
        {
            SearchList = GetCourses(q,year)
        };
        var results = model.SearchList.Items.ToList();
        int count = results.Count();
        int resultCount = 0;

        if (callback != "")
        {
            jsonbuilder += callback + "(";
        }
        jsonbuilder += "[";
        foreach(var result in results)
        {

            if(resultCount+1 == count)
            {
                jsonbuilder += "{\"title\":\"" + result.Fields["title"].ToString() + "\"}";
            }
            else
            {
                jsonbuilder += "{\"title\":\"" + result.Fields["title"].ToString() + "\"},";
            }

            resultCount++;
        }
        jsonbuilder += "]";
        if (callback != "")
        {
            jsonbuilder += ")";
        }
        return new ContentResult { Content = jsonbuilder, ContentType = "application/json" };
        //return Json(jsonbuilder, JsonRequestBehavior.AllowGet);
    }

感谢您帮助诊断问题Thanigainathan。