Search code examples
javascriptasp.net-mvc-4razorviewdata

How to pass ViewData from Controller to my JS


I have the below scenario where I am passing data from my controller to view

CONTROLLER:

  public ActionResult Create(string ID)
        {
            if (ID!= null)
            {
                int nid = Convert.ToInt32(ID);
                DataWiz NDW = new DataWiz();
                ViewData["Filter"] = NDW.Filter(nid);
            }
            return View();
        }

VIEW (Razor):

    @{
            var Filter = ViewData["Filter"];
    }
@section Create(//this is rendered in from Layout)
    {
    <script src="@Url.Content("~/Scripts/Create.js")" type="text/javascript"></script>

}

When I debug the View I am able to see the data in Filter but how do I get this to my JS in the document ready function.

JAVASCRIPT:

$(document).ready(function () {
    var test = '<%= ViewData["Filter"] %>';
    });

I have my js rendered from Layout and not using the tag in my razor view

Is this the right way to get VIEWDATA from controller to the JS if so what am I doing wrong?


Solution

  • After few attempts I found this as one way to access the ViewData or ViewBag in my JS

    I used the KO JS optionsAfterRender as below

    VIEW

    <select  data-bind="options: SubType, value: selectedSubType, optionsValue:'SubTypeID', optionsText:'SubTypeDescription',optionsAfterRender:function(){setOptionST(@Filter.SubTypeID);}"></select>
    

    JS

    In the view model

     self.setOptionST = function (x) {
            //here we can do whatever is intended to in my case to set the initial value in dropdown
            self.selectedSubType(x);
        };