最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Access ViewBag in JS file - Asp.net MVC - Stack Overflow

programmeradmin0浏览0评论

I have one Viewbag. I have fill that viewbag value from server side in Action result method. I need to access this Viewbag value in Js file. I have access this Viewbag in *.cshl page properly. Here below shown my sample code,

Var objMode = '@ViewBag.Mode'; //Written in *.cshtml page.

but i need to access this value like above syntax in *.js file.

Thanks, Nirav Parikh

I have one Viewbag. I have fill that viewbag value from server side in Action result method. I need to access this Viewbag value in Js file. I have access this Viewbag in *.cshl page properly. Here below shown my sample code,

Var objMode = '@ViewBag.Mode'; //Written in *.cshtml page.

but i need to access this value like above syntax in *.js file.

Thanks, Nirav Parikh

Share Improve this question edited Mar 26, 2013 at 11:45 tereško 58.4k25 gold badges100 silver badges150 bronze badges asked Mar 26, 2013 at 11:43 KCS NiravKCS Nirav 531 gold badge1 silver badge4 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 10

You can't. You can write ViewBag value in hidden input and then read it from js file:

<input type="hidden" value="@ViewBag.Mode" id="mode" />

JS file:

var mode = document.getElementById('mode').value;

EDIT: Another option:

<script src="..." type="text/javascript" onload="InitMyScript('@ViewBag.Mode')"></script>

JS file:

function InitMyScript(mode){
   //other code here
}

You can't reference ViewBag or other context items in included script files because those are served as static files and not processed on the server (if you need, this can be worked around by serving a View with the content type of JavaScript).

You need to put the value in your view as JS variable:

<script type="text/javascript">
    // the object is only required if you want a nice syntax for multiple values.
    if (!window.ViewBag) window.ViewBag = {};
    window.ViewBag.Mode = @Html.Raw(Json.Encode(this.ViewBag.Mode));
</script>

Now you can reference it in your script file.

发布评论

评论列表(0)

  1. 暂无评论