1

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?

sss111
  • 349
  • 1
  • 7
  • 27
  • possible duplicate of [Mix Razor and Javascript code](http://stackoverflow.com/questions/5614941/mix-razor-and-javascript-code) – Mark C. May 15 '15 at 18:53
  • I have my js rendered from Layout and not using the – sss111 May 15 '15 at 18:58

2 Answers2

0

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);
    };
sss111
  • 349
  • 1
  • 7
  • 27
-1

Use below:

<script type="text/javascript">
    var test = <%= serializer.Serialize(ViewData["Filter"]) %>;
</script>

Or

May be this one will help you out.

Solution 1

Solution 2

Community
  • 1
  • 1
Mahavirsinh Padhiyar
  • 1,299
  • 11
  • 33