简体   繁体   中英

JQuery Autocomplete in MVC3

Sorry I'm very new to JQuery... I can't for the life of me figure out where my bug is. When I run this I don't get any results. When I check the error in Firefox and Chrome it points to the source line. I just can't see anything wrong.

Here's my script

<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/modernizr-1.7.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery-ui-1.8.11.js")" type="text/javascript"></script>

<script type="text/javascript">
    $(document).ready(function () {
        $('#CustName').autocomplete({
            //Firefox points to a syntax error here
            source: @SqlHelper.getJSONArray("CustName", "dba.BillingInfo") 
        });

    });
</script>

<p>Customer Name @Html.TextBox("CustName")</p>

SqlHelper.getJsonArray is a method I'm using to return a JSON string. I've checked and double checked that it is in fact returning valid JSON.

    public static string getJSONArray(string column,string table)
    {            
        string qry = "SELECT DISTINCT " + column
                    + " FROM " + table
                    + " WHERE " + column + " is not null"
                    + " AND " + column + " <> ''"
                    + " ORDER BY 1";

        List<string> result = new List<string>();

        SqlDataReader reader = execQry(qry);

        while (reader.Read())
        {
            result.Add(reader[0].ToString());
        }

        JavaScriptSerializer serializer = new JavaScriptSerializer();

        return serializer.Serialize(result);
    }

[UPDATE] Here is the syntax error firefox is spitting back:

source: $.parseJSON([&quot;Customer1&quot;,&quot;Customer2...
---------------------^

So I'm beginning to think the issue is the quotes are getting rendered as quot; instead of ". If I try putting my source as ["Test1","Test2","Test3"] it works fine. Is there a way to get razor to not HTML encode the string?

[UPDATE] That was the issue. The solution was using Html.Raw()

The issue was razor automatically HTML encoding the JSON. The fix is using HTML.Raw

$('#CustName').autocomplete({
    source: @Html.Raw(SqlHelper.getJSONArray("CustName", "dba.BillingInfo")) 
});

Try using $.parseJSON .

$(document).ready(function () {
   $('#CustName').autocomplete({
       //Firefox points to a syntax error here
      source: $.parseJSON(@SqlHelper.getJSONArray("CustName", "dba.BillingInfo"))
   });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM