MVC C# Code in Javascript - c#

On a cshtml page in my View i easily get the URL to an action with thise line:
<h1>#Url.Action("NewComment", "Case")</h1>
And if I write this in Javascript:
<script>
alert('#Url.Action("NewComment", "Case")');
</script>
It also comes up correct in the alert.
However my problem is that at the bottom of the page I have several other javascript beeing referenced like this:
<script src="~/Scripts/custom/SomeScript.js"></script>
And if I write alert('#Url.Action("NewComment", "Case")');
In that file. It just comes up as #Url.Action("NewComment", "Case") in the alert box.
So how come it doesn't work in this file?
In the same file I also have a click method with $.ajax({ method and the url is referenced like this: url: '#Url.Action("NewComment","Case")', and here it works fine again.
So how come it works here again? Is it something with that Ajax method is a Jquery Object??
The spesific problem I have is that I need to reference the URL.Action method i the Ajax call of a Jquery Datatable.
var table_comment= $('#comment_table').dataTable({
"sDom": "<'dt-toolbar'>",
ajax: {
url: "/Case/NewComment/", //This works but want to change it to use URL Action
url: '#Url.Action("NewComment", "Case")', //don't understand why this doesn't work
type: "POST",
data: {"id": Case_ID }
},

The reason that #Url.Action("NewComment", "Case") works in *.cshtml, is that it is rendered to HTML on the server by ASP.NET MVC. As for your *.js files, these are not transformed by ASP.NET MVC, so what you see is what you get.
Specifically, .cshtml files are C# Razor templates, which get rendered by ASP.NET MVC to .html files.
As for your .js files, perhaps you could work around this by defining your URLs as global variables in your .cshtml, which you simply refer to in your .js files.
<script>
var newCommentUrl = '#Url.Action("NewComment", "Case")';
</script>

You cannot write Razor syntax inside separate js file because after all its Razor syntax '#' which only
Razor engine could interpret(and could be written inside .cshtml extension Pages only) and razor engine
convert it to appropriate HTML so that is why
in separate js file file when you write alert("#Url.Action("NewComment", "Case")") it comes as
#Url.Action("NewComment", "Case")

You can't have razor syntax ( #Url.Action ) inside a linked JavaScript file - Visual Studio doesn't work like that.
As a solution, write out your variables in javaScript in your CSHTML file like so:
<script type="Text/javascript">
var dataTableURL = '#Url.Action("NewComment","Case")';
</script>
And then underneath this reference your external javascript file
<script src='#Url.Content("~/Scripts/MyJavaScriptFile.cs")' type="text/javascript"></script>
And modify your javscript variable to use the above variable:
var table_comment= $('#comment_table').dataTable({
"sDom": "<'dt-toolbar'>",
ajax: {
url:dataTableURL,
type: "POST",
data: {"id": Case_ID }
},

I found out a way better solution for this!
RazorJS :) Works perfect.
http://www.nuget.org/packages/RazorJS

Related

How do I inject javascript code via webview?

Basically what I want to do is this this but I can't seem to find something similar for webview XAML control. What I ultimately need to do, is capture an incoming json file from the webview. As is, I get a bad request from the server and unsupported file exception from the webview. I thought about injecting a javascript so that it would alert me, I could get the body of the incoming json and bypass all the errors.
There are two main things you can do:
Call functions programically
Inject any code by using the HTML string
Function Calling
You can use InvokeScript to call javascript functions.
If you have in a webpage with a script:
<script lang="en-us" type="text/javascript">
function myFunction() {
alert("I am an alert box!");
}
</script>
Then you can in C# call:
MyWebview.InvokeScript("myFunction", null);
Which will execute the script function myFunction.
Injecting Text
If you download the HTML page and all other needed files(using the Windows HttpClient), you can inject any code by manipulating and then Navigating to string.
Lets say you want to change the above script to add another function, "HelloWorld", then you can
Search the file for something you know will be there, such as: <script lang=\"en-us\" type=\"text/javascript\">
Using string manipulation, add the desired text, such as a function (but this can be anything)
Navigate to the String
The C# code:
string MyWebPageString = GetWebpageString(WebpageUri);
string ScriptTagString = "<script lang=\"en-us\" type=\"text/javascript\">";
int IndexOfScriptTag = MyWebPageString.IndexOf(ScriptTagString);
int LengthOfScriptTag = ScriptTagString.Length;
string InsertionScriptString = "function SayHelloWorld() { window.external.notify(\"Hello World!\");} ";
MyWebPageString = MyWebPageString.Insert(IndexOfScriptTag + LengthOfScriptTag + 1, InsertionScriptString);
MyWebview.NavigateToString(MyWebPageString);
The result will be that the navigated to Webpage will look like this:
<script lang="en-us" type="text/javascript"> function SayHelloWorld() { window.external.notify("Hello World!");}
function myFunction() {
alert("I am an alert box!");
}
</script>
Since the injection can be applied to any area, even the HTML, you should be able to figure something out.
Hope this helps. Good luck.
This answer was based on this MSDN blog

Create new Script within <div> from C# and Reload newly created Script

I would like to implement the following, which would appear to be fairly easy, but I have been searching for a working example without success.
i) I have an HTML Tag in an aspx Page with an identification:
<div id="demo" runat="server">
ii) This Tag contains the following Script Tag, which itself has an identification:
<script id="scriptdemo" type="text/javascript" src="http://www.myurl.com/myquery"></script>
iii) I have an AJAX call which calls a Server Function (which is working without any issue)
iv) From that Server Function, I would like to either modify the “src” Attribute of the Script, or create and insert a new script in the existing division with a new src if this solution is easier to implement.
v) After executing the Server Code contained within the Server Function, the flow is properly passed back to the client (here again, I do not have any issue with this process).
vi) Once back on the client, I would like to refresh/reload the newly created script (or updated src attribute) using JavaScript/AJAX (either standard Javascript or JQuery).
Would someone have a working example of such code?
Check out http://api.jquery.com/jQuery.getScript/
It's basically shorthand for $.ajax with datatype as "script". This will load a script file for you, and give you the chance to run a callback when it's done.
$.ajax({
url: "your/ServerMethodThatReturnsScript",
dataType: "script",
success: successCallback
});
becomes
$.getScript("your/ServeRMethodThatreturnsScript", function() { /* some success callback */ });
In the event you can't do this but CAN make an ajax call to your server, you can use the eval method to execute any string that is in the form of javascript:
eval("/*some javascript*/");

#Url.Action inside $.get

I've seen a few posts about this but stills couldn't understand why this is not working
$.get('#Url.Action("Edit","Contacts")', {id: parseInt($(this).attr('id')) } , function (result) {
obviously this does
$.get("/Contacts/Edit/" + parseInt($(this).attr('id')), function (result) {
I've tried with replacements and still getting the proper id but the #Url.Actions appears as a string itself generating weird routes as this one for the former code, seems to me that the url.action is not executed, right?
localhost:53720/#Url.Action(Edit,%20Contacts)?id=23918
Edition: Actually the route generated for that code is
localhost:53720/Url.Action(%22Edit%22,%20%22Contacts%22)?id=23918
the other is for another try I've made
Anyone can tell me why?
Thanks
To have access to HtmlHelpers inside javascript, the javascript code must be inside a View page, and not inside a javascript file
<script>
var url = '#Url.Action("Edit","Contacts")';
console.log(url);
</script>
Looks like #Url.Action is not getting called and the URL is not being returned.
var url = '#Url.Action("Edit","Contacts")';
$.get(url, {id: parseInt($(this).attr('id')) } , function (result)
If JS complains about the above, you can try specifying #: beforehand to let razor take control.

Is this possible through javascript?

I am currently working on asp.net project. I use oodle web service. Oodle provides result via URL. I use Link to get data from the URL.
From code behind I use following code to fetch the resultant string :
string url =
#"http://api.oodle.com/api/v2/listings?
key=TEST&region=chicago&category=vehicle&format=json";
var jsonString = new WebClient().DownloadString(url);
Now , My problem is I use button click event to run that code. But is this through JavaScript ? Because If I use Javascript it will be easier to access my resultant data.
It looks like this API returns JSONP which means that you could consume it directly from javascript. For example if you use jQuery you could use the $.ajax() method:
$.ajax({
url: 'http://api.oodle.com/api/v2/listings?key=TEST&region=chicago&category=vehicle&format=json',
type: 'GET',
dataType: 'jsonp',
jsonpCallback: 'jsonOodleApi',
success: function(result) {
alert(result.current.region.id);
}
});
Here's a live demo.
And if you don't use jQuery you could simply define a callback:
var jsonOodleApi = function(result) {
alert(result.current.region.id);
};
and then include a <script> pointing to this url:
<script type="text/javascript" src="http://api.oodle.com/api/v2/listings?key=TEST&region=chicago&category=vehicle&format=json"></script>
Here's a live demo.
Obviously you could inject this script tag dynamically into the DOM whenever you want to invoke the API call.
You can make Ajax requests to the page through Javascrypt.
here's a tutorial on that
If you are using some JavaScript frameworks, like JQuery, those requests would be easier to make, as the AJAX requests are kinda not cross-browser compatible.
the JQuery version
What you want is an AJAX request. It it certainly possibly to do without libraries, but due to crossbrowser issues I would recommend using a library. With jQuery for example it could look like this (in a document ready part of script):
$("#idOfButton").click(function() {
$.get('string url= #"http://api.oodle.com/api/v2/listings?key=TEST&region=chicago&category=vehicle&format=json', function(jsonString) {
alert('Data is now in variable jsonString!');
});
});

PageMethods in ASP.NET failed to work if you have ASP.NET Routing Implemented

I have a web method:
[System.Web.Services.WebMethod]
public static string getCharacterstics(int product_id, int lang_id)
{
// code goes here...
}
I want to access it using PageMethods like:
(Provided the condition that i have Enable PageMethods in ScriptManager):
<script type="text/javascript">
$(document).ready(
function () {
$('#characterstics').html("loading");
// '<%= product_id_property %>' , '<%= this.LanguageID %>'
PageMethods.getCharacterstics(0 ,0 , OnSave);
}
);
function OnSave(result) {
}
</script>
I get the error "the http verb post to access path.. is not allowed"
I googled it and search the SO too but does not get any solution regarding to it Based on ASP.NET Routing.
What i believe is that because of asp.net routing the service methods are not accessible.
In addition i think i cannot even use JSON because of asp.net routing too.
Any help is appreciated.
Updated:
If i run the page with this url:
http://localhost:2606/searchdetail.aspx
The web method executed successfully.
Now
I have routing like this:
routes.MapPageRoute("searchdetail", "searchdetail/{ID}", "~/searchdetail.aspx");
routes.MapPageRoute("searchdetail", "searchdetail", "~/searchdetail.aspx");
The set_path() will work only for case 2 i.e without ID but does not work with case 1
if i try
http://localhost:2606/searchdetail
It works fine
but if i try to use:
http://localhost:2606/searchdetail/123
It gives error that object expected.
So set_path() is the option what should i write.
Currently, WebMethods don't work transparently with the Routing framework. There is a work around. You have to access the PageMethods directly by doing the following in your javascript:
PageMethods.set_path('/the/path/to/your/page.aspx');
PageMethods.YourMethod(params, onSuccess, onFailure);
I hope this helps.
I kept running into this myself. With routing enabled, if I added a value to the path, it would start to fail again. This solution is a bit of a hack, but it seems to be working consistently.
Create a server control hyperlink where the navigate url refers to itself, then once the control renders, grab the href and use it for set_path
This gets around the issue of set_path not referring to the correct location if you called
<asp:HyperLink ID="hlPage" runat="server" NavigateUrl="~/user.aspx" ClientIDMode="Static"></asp:HyperLink>
<script>
$(document).ready(function () {PageMethods.set_path($('#hlPage').attr('href'));})
</script>

Categories