开发者

Wanting to mix server side ASP.Net MVC expansion in javascript file, but how... RenderPartial?

开发者 https://www.devze.com 2023-01-07 14:15 出处:网络
I have some common javascript functionality that I want to share across several views/pages. However I want to put some C#/ASP.net into the javascript - pulling in some data from the server.

I have some common javascript functionality that I want to share across several views/pages.

However I want to put some C#/ASP.net into the javascript - pulling in some data from the server.

It seems like the best option is to use a partial page, and include the javascript in that.

Just wondering if there is a javascript equivalent of the partial page?

Or is there another/better/alternative way of doing this?

EDIT: I r开发者_高级运维ealise I could use ajax to pull the server code in (although how do I refer to the server, Url.Content won't work) but this code is to handle page permissions, ie the server data details what functions the user can access and the javascript functions are then used to show/hide buttons based on that. So the data needs to be present early on rather than triggering the page to be built after the ajax callback happens.

Thanks in advance, Chris


I usually put some data that is needed by javascript into the top of the page.

I have it in the Masterpage.

After that I include the common js files. The variables defined at the top of page are available to the scripts. Don't forget to JavascriptEncode these values. Html-Encode is not enough, it doesn't handle the '. Use Web Protection Library for it http://wpl.codeplex.com/.

<script language="JavaScript">
var controller = <%= AntiXss.JavaScriptEncode(ViewContext.RouteValues.GetRequiredString("controller")) %>;
var userRightRead = <%= AntiXss.JavaScriptEncode(Model.UserRightRead) %>;
</script>


However I want to put some C#/ASP.net into the javascript - pulling in some data from the server

You don't need to put any C#/ASP.NET into javascript to pull data from the server. You can simply use AJAX. Example with jQuery:

$.ajax({
    url: '/home/someaction',
    success: function(data) {
        alert(data);
    }
});


I'll normally wrap the javascript up in a class and then pass in the view model values I need.

For example with this javascript:

var testClass = function(config){
    this.width = config.width;
    this.height = config.height; 

    this.showDimensions = function(){ 
        alert( this.width + " by " + this.height); 
    }
}

the view/partial view would contain:

<script>
var dim = new testClass({ 
    width: <%=Model.Width %>
    height: <%=Model.Height %>
})

dim.showDimensions();
</script>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号