2012-02-08 71 views
0

对不起,我对JQuery很新颖......我不能为我的生活弄清楚我的错误在哪里。当我运行这个时,我没有得到任何结果。当我检查Firefox和Chrome中的错误时,它指向源代码行。我只是看不到任何错误。MVC3中的JQuery自动完成

这里是我的脚本

<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是我使用的是返回一个JSON字符串的方法。我检查并确认它实际上是返回有效的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); 
    } 

[更新] 这里是语法错误Firefox是吐回:

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

所以我开始觉得这个问题是报价越来越呈现为QUOT;而不是“如果我尝试把我的源代码作为[”Test1“,”Test2“,”Test3“],它工作正常。有没有办法让剃刀不HTML编码字符串?这是问题。该解决方案是使用Html.Raw()

的问题是剃刀自动HTML编码的JSON。此修复程序使用HTML.Raw

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

你的方法返回的json是什么?什么是渲染输出? – 2012-02-08 22:09:33

+0

@DidierGhys以下是JSON输出[“Customer1”,“Customer2”,“Customer3”]的示例 – copjon 2012-02-08 22:15:18

+0

@DidierGhys并且Firefox具有$('#CustName')行自动完成({# " Customer2 "," Customer3 "] }); – copjon 2012-02-08 22:17:40

回答

1

尝试使用$.parseJSON

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

刚刚尝试过...仍然无法正常工作... – copjon 2012-02-08 22:35:11