santosh kumar patro
santosh kumar patro

Reputation: 8203

How to access ViewModel property in jquery method for asp.net mvc2 application

I am working on asp.net mvc2 application. I have a ViewModel defined as below :

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

I am filling the TestViewModel 's property EnabledSections with a list within an action method :

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();
      }
}

I need to access the EnabledSections in the jquery method :

function CheckEnabledSection(){
}

Can anyone guide me to resolve the above mentioned issue?

Upvotes: 0

Views: 1864

Answers (1)

Justin Bicknell
Justin Bicknell

Reputation: 4808

Firstly, you must pass your view model into your view, so from within your action it would look something like:

return View("ViewName",model);

Also, be sure to declare the type of model within your view:

@model TestViewModel

Then from within your view, you need to add any information from the model into your js:

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

</script>

Now you can access the js variable enabledSections within your javascript

Upvotes: 2

Related Questions