2013-04-23 65 views
0

我正在研究asp.net mvc2應用程序。我有一個視圖模型定義如下:如何在jquery方法中訪問ViewModel屬性的asp.net mvc2應用程序

public class TestViewModel 
    { 
     /// <summary> 
     /// Get and Set the EnabledSections 
     /// </summary> 
     public List<string> EnabledSections { get; set; } 
    } 

我盡顯TestViewModel的財產EnabledSections與列表的操作方法中:

public ActionResult TestAction(Student student, string[] sections = null) 
{ 
     var model = new TestViewModel 
     { 
     EnabledSections = model.TestSections.Where(s => s.Value.Item2 == true).Select(s => s.Key).ToList(); 
     } 
} 

我需要訪問jQuery的方法EnabledSections:

function CheckEnabledSection(){ 
} 

任何人都可以指導我解決上述問題?

回答

2

首先,你必須通過你的視圖模型到你的觀點,所以從你的行動中,它看起來是這樣的:

return View("ViewName",model); 

另外,一定要在視圖裏聲明的模型類型:

@model TestViewModel 

然後從您的視圖中,您需要從模型中的任何信息添加到您的JS:

<script> 
    @{ 
    var jsSerializer = new JavaScriptSerializer(); 
    } 
    var enabledSections = @jsSerializer.Serialize(Model.EnabledSections);//serialize the list into js array 

</script> 

現在您可以訪問您的javascript中的js變量enabledSections

+1

非常感謝。上述方法爲我工作:) – 2013-04-24 06:54:07

相關問題