How to pass ViewData from Controller to my JS

只谈情不闲聊 提交于 2019-12-08 05:46:06

问题


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?


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/30266755/how-to-pass-viewdata-from-controller-to-my-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!