#Url.Action inside $.get - c#

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.

Related

MVC C# Code in Javascript

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

Button Not Working Without Refreshing Page

I am building a website with some simple functions and I'm running into some issues. I can't provided any sample code because I have no idea where the problem lies and technically the site is not crashing.
The frontend of the site is html and javascript, the backend I'm using ASP.Net and C#.
There's a button on the page, which will trigger a function in javascript. The function will then make a call to the backend aspx file (say, myFunction.aspx) and generate a output file for the user to download.
Everything is working just fine. I was getting the expected result and was able to download the output file with no problem.
I didn't notice the issue until I try to re-run this function.
I hit the button again but it wasn't doing anything (I was also using Httpfox so I know it's not calling anything)
I realize that I wasn't able to run the function again without refreshing the page. After refreshing the page it works just fine.
Can anyone explain why its this way? How can I go about debugging this issue? I don't even know if the problem is with the fontend or the backend.
Thanks for the help.
EDIT
This is how I created the button.
<button dojoType="dijit.form.Button" type="button" onclick ="myJSFunction('uploadForm')">Generate</button>
and this is how the function is calling the asp backend
var myJSFunction= function (formId) {
dojo.io.iframe.send
({
url: 'myURL/myFunction.aspx?parameter=p',
form: dojo.byId(formId),
method: "POST",
handleAs: "text",
load: function (response, ioArgs) {
dojo.byId("timeStamp").value = response;
}
error: function (response, ioArgs) {
alert("Failure:" + response);
}
});
}
EDIT 2
I just notice something interesting.
I have been running in Firefox using HttpFox and was not getting any error message. Then I tried to run it in Chrome using F12 and I'm getting red alerts.
In Chrome, under the Network tab, the status says "canceled", but I was still getting the output.
How could this happen? How can I find where the issue is?
Check your javascript console to see that you don't have any errors on the page. Otherwise post your asp.net markup for the button and the javascript function.
Edit:
Try returning false from your javascript function. This will prevent the default browser behavior from executing (What's the effect of adding 'return false' to a click event listener?)
A workaround might be to unnbind and then rebind the click event on your element so every click is effectively the "first", to avoid anything that dojo or something else may be doing out of your control. I don't know dojo, but based on http://dojotoolkit.org/reference-guide/1.9/dojo/on.html#dojo-on the following should be about right:
var updateHandle;
var myJSFunction= function (formId) {
updateHandle.remove();
dojo.io.iframe.send
({
url: 'myURL/myFunction.aspx?parameter=p',
form: dojo.byId(formId),
method: "POST",
handleAs: "text",
load: function (response, ioArgs) {
dojo.byId("timeStamp").value = response;
updateHandle = on(your.buttonElement, "click", function(){
myJSFunction(formId);
});
}
error: function (response, ioArgs) {
alert("Failure:" + response);
}
});
}
updateHandle = on(your.buttonElement, "click", function(){
myJSFunction("myFormId");
});
Thank you all for the help and suggestion.
I have found the solution to the issue. All I need is a single line to the frontend code.
dojo.io.iframe._currentDfd = null; //add this line
dojo.io.iframe.send
({...
});
Thanks for the help.

Call C# function from Javascript in aspx webform and then reload page

Trying to figure out how to call a c# function in a webform. I tried both ajax and windows.location but could just be off on my path. Trying to send it my c# code at SpeakerList.aspx/update and then gonna attach two variables i have in javascript which shouldnt be too bad. But want it to hit the C# function then reload the page so hoping there is just an easy call im missing.
buttons: {
"Save": function () {
var combo = ASPxClientControl.GetControlCollection().GetByName('DropDownList1');
var value = combo.GetSelectedItem().value;
var billID = $("#billID").val();
window.location = "SpeakerList.aspx/updateRec";
}
You might want to try using WebMethods:
http://aspalliance.com/1922_PageMethods_In_ASPNET_AJAX.all
This allows you to call a function in your page's code behind using JavaScript.
Assuming you are using MVC, you probably want to return a JSON result. An easy way to consume Json within your client webpage is using JQuery. You can return JSON as as the output of a webpage, but I don't recommend it. Create a separate service point that repesents the JSON method.
It is hard to tell what you are actually trying to accomplish, but the normal usage pattern for a JSON method is the supply the parameters as part of the querystring (which you can refactor with routing if you want). The result is then just a JSON packet.
Personally, I like JSON.Net for server side JSON, but you don't actually need this. Look up JSONMethod for examples, etc. that will show you how to do this.
From the browser client, JQuery has a json method, but I personally recommend using the more generic ajax method a JQuery so you can use the handlers for success, error and completion. E.g.
$.ajax({
url: "http:...",
data: queryparm,
cache:false,
timeout:15000,
success: function(data){
jresult = $.parseJSON(data);
...
},
error:function (xhr, ajaxOptions, thrownError)
{
setErrorMsg("Error getting search results: " + thrownError);
}
});
EDIT -- Actually, I've done this exact same thing with webforms too, code is essentially identically (if you use JSON.Net on the server side). You don't have the routing options to make the urls REST compliant, but as an internal json web service, you probably won't really care about that.
As a webpage (.aspx) page, you can use a "postback" this is the simplest method for a web form. You can always declare some hidden fields to use for data passing if you are not passing back a native "control" value. If you don't know how to do this, you need to read a tutorial on using web forms.

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>

jQuery does not load response

I normally use ASP.NET MVC 2, but there were some problems with it, so I began to work with ASP.NET MVC 2 + jQuery and everything works. But there is one problem, jQuery doesn't load my reponse. On the ASP.NET MVC side I'm redering a partial view and I also get the respone on the client, but nothing is rendered. How can I solve this?
Here is the jquery code:
function addCredential(state, id) {
var daten = getJson(state, id);
$.ajax(
{
type: "POST",
url: "/Account/SetCredential/",
data: daten,
dataType: "json",
success: function(partialView) {
$('#Credentials').replaceWith(partialView);
location.reload();
}
});
return true;
};
function getJson(state,id) {
var username = $('#username').val();
return {"username": username, "credential_id": id , "state": state };
};
The problem looks like location.reload();
That's reloading your page after you update it with AJAX, effectively returning it's state back to the way it was before you inserted the content with .replaceWith()
UPDATE: looks like you're using dataType: "json" and inserting that into the DOM? That's probably also a problem. If the view is being returned as HTML, you should replace that with dataType: "html"
#Konrad, try using the JSON2 library (http://www.json.org/js.html) to alert the "partialView" object in your success function to see what you're getting prior to reloading the page. Also, make sure $('#Credentials') is returning an object. When I run into issues when trying to select elements on the page, I usually check the length value of the jQuery object that is returned. If length = 0, then you're not getting the element.
UPDATE:
Also, if you're trying to inject HTML into $('#Credentials'), then partialView may not be the correct format. The success function accepts an object argument which comes from parsing of the responseText of the web method you called to get what you call partialView.
UPDATE:
Check http://encosia.com/2010/03/03/asmx-and-json-common-mistakes-and-misconceptions/ for more info using $.ajax. Lots of great info on this blog.
UPDATE:
This is how I use JSON lib to view the data that is returned.
alert(JSON.stringify(partialView));

Categories