Why moving the code from html into .js causes issue? - asp.net-mvc

I have asp.net mvc project with knockout.js so my index page is getting really huge because of lots of javascript functionality.
I'd love to move js code into a separate file but it does not allow me to apply it to the most of the code because if I have something like
$.ajax({
url: "#Html.Raw(#Url.Action("Load"))",
Then it pops up a error if I move this part of the code into another file.
Please advise how can I resolve this issue?

Javascript files are not parsed by ASP.net, so the variables you have of #Html.Raw and #Url.Action("Load") will never be processed.

As #James Lai noted, server side code isn't parsed as such by ASP.Net. See this post for a workaround, or you can pick and choose which scripts can still stay on the page (with server-side code) instead of the "everything" - your choice as to which approach meets your requirements.

Javascript files are not parsed by ASP.NET MVC, thus #Html.Raw(#Url.Action("Load")) will not work in javascript file.
Heres workaround
Instead declare a variable in view.cshtml. In script section as
<script type="text/javascript">
var actionUrl = '#Url.Action("Load", "Controller")';
</script>
And use actionUrl in javascript file.

Related

MVC HTML helper wrapper for jqPlot

I wish to create an MVC wrapper around jqPlot.
I want to have a helper object to render the required html container element and the required java scripts to draw the chart.
Something that will look like this:
#Html.jqPlot()
.ChartType(eChartTypes.PieChart)
.ChartData(someData)
.RenderChart();
Now I'm only at the initial design phase and I know what the jqPlot object should look like to achieve that, the problem I'm having is with the java script that suppose to be emitted to draw the actual chart using jqPlot.
Suppose I will render the following script in my .RenderChart() method
public string RenderChart()
{
string chartCode = string.format(#"
<script type="text/javascript" src="../src/plugins/jqplot.canvasTextRenderer.min.js"></script>
<script type="text/javascript" src="../src/plugins/jqplot.canvasAxisLabelRenderer.min.js"></script>
$(document).ready(function(){
var plot1 = $.jqplot ('{0}', [{1}]);
});
",this.ChartGuid, this.ChartData);
return chartCode;
}
The above is not actual code but just a general representation of the idea.
So the problem is that i don't want the Helper to emit the JS code into the body of the Html document, furthermore i cannot let it do that becuse some of the required scripts may be at the bottom of the html (as the best practice states).
Any suggestions ?
What would be the best way to emit JS code using an HTML helper if the situation requires it (like this one) ?
I think, listening to an even will be a possible solution, in this case the even of outputting or finishing the rendering of the footer. so maybe your code will give as an option to listen to an event and render at that moment, but this is of course platform dependent. I also worked on a php wrapper you can fork it here: https://github.com/oumsofiane1/jqplotPHPwrapper.git
and just implemented a helper, but of course you can extend that :-)
Hope this helps

Backbone With Rails

I'm getting my data from a service and then setting the data to my bean object and want to using the same data in my view displaying it in a form in rails view now. Now I want to validate this form using backbone.
I'm new to both Rails and Backbone.
Kindly give me an idea on how to proceed on this.
I think perhaps you are confused about how web applications work. Backbone is a client-side framework; it uses Javascript code that is run in your users' browsers. Rails is a server-side framework; it uses Ruby code that runs on your server.
Given all that, your Backbone code and your Rails code by definition have to be completely separate. The two can communicate in only two ways:
1) Your Rails code can write <script> tags to the page (inside a .html.erb file) and put variable data there; for instance:
<script>
var myVarFromRails = '<%= someRailsVariable %>';
</script>
When that comes back from the server (ie. when you view source the page) that will get converted to:
<script>
var myVarFromRails = 'foo';
</script>
(assuming 'foo' was the value of someRailsVariable).
2) Your Javacript code can make AJAX requests to Rails URLs, and whatever the Rails code spits out there will come back as the response to your AJAX request. In other words you can do:
$.ajax({url: someRailsUrl, complete: function(response) {
// whatever the server sent back will be inside the "response" variable
}});
Other than that the two are pretty much entirely separate, and if you want to do the same thing in both of them (eg. validate a form) you essentially have to write the code twice, once for Ruby and once for Javascript.
I say "essentially" because there are Rails plug-ins which do #1 and #2 for you in different ways. I'm not a Rails expert, and even if I was there are so many of these plug-ins that you really need to look for yourself to find out what exists and what makes sense for your codebase.
Hope that helps.
* EDIT *
I know I just said I wouldn't list libraries, but then I realized it'd be more helpful if I at least provided a few to get you started. Just don't take these as canon; they're simply some popular libraries at the moment, but they may or may not be right for you.
https://github.com/codebrew/backbone-rails
https://github.com/meleyal/backbone-on-rails
https://github.com/aflatter/backbone-rails
https://learn.thoughtbot.com/products/1-backbone-js-on-rails
http://kiranb.scripts.mit.edu/backbone-slides/
That last two aren't actually libraries, they're a book/presentation, but I thought they might be useful.

How to localize javascript files in a Struts 2 app

I wrote an Struts 2 application and want to localize it. Now I am using javascript and I would like to put the scripts out of my HTML template to an own javascript file.
When I do it, my s:text tags are not rendered (of course).
Question is how can I localize my javascript files with Struts 2 in a clean way? I would like to avoid to use another technique than the properties files i currently use.
Thanks,
Christian
If you want to stick with your resource bundles back at server, one way possible would be to save your javascript files as .jsp file and serve them with an action so this way your struts tags in your javascript files will get a chance to retrieve the data from server and return the file upon request.
Personally I prefer to keep client messages in javascript files and server messages in resource bundles. This way you can save a .jsp processing IMHO.
You can use a hidden field in your JSP and pass its id to the external JavaScript file and get its value like follows.
In your JSP,
<s:hidden id="warning" value="%{getText('propertyKey')}"/>
(hidden field poplated with the value of the property key in the resource bundle)
Call your external JS method from the same JSP,
<s:a href="%{deleteSelected}">
<img src="<s:url value='/images/delete.gif'/>" border="none"
onclick="javascript:return displayWarning('warning')"/>
</s:a>
In external JavaScript file,
function displayWarning(message) {
var ret = true;
ret = confirm(document.getElementById(message).value);
return ret;
}
<script type="text/javascript">
var mytxt='<s:text name="my.text.prop" />';
alert(mytxt);
</script>
This is also possible, but you cant have them inside a function.You should assign relevant properties to global JS variable at the time of page load. Almost same concept slimier to use hidden variables.

ASP.NET MVC editor template javascript location

We have an editor template that contains approx 40 lines of jquery. I tried dropping this script into a <asp:Content> block to keep all of the javascript in one location within the page. However, I get the following error message content controls have to be top-level controls in a content page.
Is there any way to get this working so we don't have script dotted around our final output pages or could someone recommend the best practice for storing javascript used within ASP.NET MVC templates? At the moment I'm thinking of pulling the code into a separate file and referencing it within the master page but this means it gets pulled into every page which isn't really ideal.
Thanks in advance.
It would be easier for later maintenance, if you keep the javascript into a separate file and reference it where ever it is needed. Also, if you feel that placing all script into a single file will increase unnecessary loading of scripts, where not needed, then break the scripts into separate files based on functionality/modules in which it is useful etc. strategy and then reference them instead.
Also, it was said that always, keep/reference the scripts at the bottom of the page so that page loading will be faster.
as siva says, bottom of the page is the 'ideal'. however, as for seperate files. this is only going to be practical as long as you don't reference asp.net elements from the page - ie:
<asp:Content ContentPlaceHolderID="jsCode" ID="jsCode1" runat="server">
<script type="text/javascript">
$(document).ready(function() {
getPoundsData();
});
function getPoundsData() {
var id = $("#ID").val();
var URL = '<%=Url.Action("GetPounds", "FundShareholder")%>';
var params = { id: id };
if (id != null)
SendAjaxCache("#" + $("#ShareholderID option:selected").text() + " RSP#", URL, params, null, ListDataShareholderPounds);
}
function ListDataShareholderPounds(data) {
if (data.length != 0) {
$('#shareholderPounds').html("");
$('#shareholderPounds').show();
$('#shareholderPounds').html(data);
}
};
</script>
</asp:Content>
notice the:
var URL = '<%=Url.Action("GetPounds", "FundShareholder")%>';
part in the js. what 'we' do is to add a content section to the master page at the very bottom to hold our js stuff. however, this only works inside the ViewPage (aspx) object. the ascx pages are 'ignorant' of any master page content sections.
We are currently working on systemizing the process whereby we save 'partial' js files with asp.net references inside them and then inject them into the page-flow via a filterattribute. we're at an early stage with this but the nice thing about this approach is that the partial js is treated as a file and is therefore cached for future visits to that page.
anyway, that's our current approach, would be interested to discover if peeps are using any similar mechanisms to inject js that contains asp.net object references.
cheers...
[edit] - here's a heads up on the approach i'm talking about (this wasn't our original inspiration, but is quite similar, tho is webforms, rather than mvc) - http://www.west-wind.com/WebLog/posts/252178.aspx or this one which IS mvc: http://poundingcode.blogspot.com/2009/12/injecting-javasript-into-aspnetmvc-with.html.
Finally found the article that inspired our 'search' in this: ASP.NET MVC routing and paths is js files plus http://codepaste.net/p2s3po

Using JQuery with ASP.NET MVC Framework

I have searched the forum, and google for this topic. Most of the articles are talking about using JSON to call the controller/action on the server and do ajax effect on the result.
I am trying to use some very basic JQuery features, like the JQuery UI/Tabs, and JQuery UI/Block for a dialog window. I cannot get these simple samples to work in my MVC project. Any ideas how I should modify these samples? I only need these basic feature now and I can go from here.
Thanks!
Actually I just got it working. The problem is that I need to modify the path to an absolute path to the view page because the relative path doesn't work with the MVC routes {controller}/{action}/{id}.
Thanks!
For info, re the relative path issue - I discussed this here (the same concept applies to any page, not just master pages). The approach I used is like so:
1: declare an extension method for adding scripts:
public static string Script(this HtmlHelper html, string path)
{
var filePath = VirtualPathUtility.ToAbsolute(path);
return "<script type=\"text/javascript\" src=\"" + filePath + "\"></script>";
}
2: when needed (for example in the <head>...</head>) use this method:
<%=Html.Script("~/Scripts/jquery-1.2.6.js")%>
The advantage of this is that it will work even if the web app is hosted in a virtual directory (i.e. you can't use "/Scripts" because you aren't necessarily at the site root) - yet it is a lot clearer (and less messy) than the full script with munged src, i.e.
<script ... src="<%=Url.Foo(...)%>"></script>
I just implemented the jquery autocomplete textbox in one of my asp.net project. I only had to import the js file and drop some code into my aspx page. Could you be more detailled about what sample you are trying to run?
This is quick response!!
I am trying to run this "Simple Tabs" on this page:
http://stilbuero.de/jquery/tabs/
I think it is the same with this one: http://docs.jquery.com/UI/Tabs
I just copied and pasted the whole thing into my MVC view page, with corrected path to the jquery.js and .css files, but the content in the tabs all show up together (two of them are supposed to be hidden). My understanding is that this simple jquery plugin just show and hide content.
I had the exact same problem with the jquery thickbox plugin, that the item marked as "hidden" (the dialog box) will always show up in my MVC view page.
I can understand some of the MVC+Jquery+json articles, but I don't understand why the hide/show doesn't work.
Thanks!
I just made a walkthrough on how to do this:
http://blogs.msdn.com/joecar/archive/2009/01/08/autocomplete-with-asp-net-mvc-and-jquery.aspx

Resources