2013-04-23 67 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

相关问题