如何从控制器传递的ViewData我的JS [英] How to pass ViewData from Controller to my JS

查看:800
本文介绍了如何从控制器传递的ViewData我的JS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下场景:我从我的控制器将数据传递到浏览

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

控制器:

  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(剃刀):

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

}

当我调试视图我能看到的数据过滤器但是我怎么在文档准备功能得到这个我JS。

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"] %>';
    });

我从布局呈现的,而不是使用标签在我的Razor视图

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

这是从控制器获得的ViewData的JS如果是这样我在做什么正确的方法错了?

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

推荐答案

几次尝试后,我发现这是访问ViewData的或ViewBag在我JS的一种方法

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

我用KO JS的 optionsAfterRender 如下

查看

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

JS

在视图模型

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

这篇关于如何从控制器传递的ViewData我的JS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆