2012-07-09 48 views
0

我在頁面上有一個JavaScript需要在此格式的字符串列表:添加字符串列表中的javascript asp.net的MVC

var availableTags = [ 
     "ActionScript", 
     "AppleScript", 
     "Asp", 
     "BASIC", 
     "C", 
     "C++", 
     "Clojure", 
     "COBOL", 
     "ColdFusion", 
     "Erlang", 
     "Fortran", 
     "Groovy", 
     "Haskell", 
     "Java", 
     "JavaScript", 
     "Lisp", 
     "Perl", 
     "PHP", 
     "Python", 
     "Ruby", 
     "Scala", 
     "Scheme" 
    ]; 

我的視圖模型包含字符串命名blogtags的列表。 如何將viewmodel中的列表添加到javascript中。

感謝 ARNAB

回答

0

我想補充一個字符串類型持有逗號分隔標籤,我的視圖模型

public class BlogPostViewModel 
{ 
    //Other properties  
    public string Tags { set;get;}  
} 

在我的控制研究,我將這個值從字符串

的列表
public ActionResult View(int id) 
{ 
    var vm=new BlogPostViewModel(); 

    List<string> tagList=new List<string>(); 
    tagList.Add("PERL"); //get from your DB instead of hardcoding 
    tagList.Add("RUBY"); 

    StringBuilder strTags = new StringBuilder(); 
    foreach (var item in tagList) 
    { 
    strTags.Append("\""+item+"\","); 
    } 
    vm.Tags=strTags.ToString(); 
    vm.Tags= vm.Tags.TrimEnd(','); //remove last , 
    return View(vm); 
} 

並在視圖

$(function() {  
    var items=[@Html.Raw(Model.Tags)] 
    alert(items); 
}); 
+0

結果是var availableTags = [「ActionScript」,「AppleScript」,「asp」,「php」,] 我需要擺脫最後的',' - tx – Arnab 2012-07-09 20:08:20

+0

@Arnab:修剪最後一個字符。看到我更新的答案, – Shyju 2012-07-09 20:14:37

+0

謝謝,它完美的作品 – Arnab 2012-07-09 22:25:10

相關問題