i have a project in mvc 4 entity framework and call the controller method with ajax.
My problem is when i am using my app local, url is "Controller/Method" but when i publish i have to change url to "http://domain/appName/Controller/Method"
who can i do to get absolute path on ajax url??? my ajax is on js file and i can't use function like html.actionlink
example:
$("#btnAnswer").click(function () {
$.ajax({
url: "http://domain/appName/Controller/method/",
//url: "/Controller/method/",
data: { answer: $("#answer").val(), question_id: $("#question_id").val(), answer_id: $("#answer_id").val() },
success: function (result) {
alert(result);
}
}).error(function () {
}).fail(function () {
});
});
You don't really need the absolute url. Correct relative url is fine.
You should use the Url.Action helper method to generate the correct relative path to your action method. This will generated the proper path irrespective of your current page/view.
url: "#Url.Action("ActionMethodName","YourControllerName")"
Url.Action helper method will work if your javascript code is inside a razor view. But if your code is inside an external js file, you should build the relative url to your app root using Url.Content("~") helper method and pass that to your js code via a variable as explained in this post . Try to use javascript namespacing when doing so to prevent possible conflict/overwriting from other global variables with same name.
EDIT : Including Marko's comment as an alternate solution. Thank you :)
If it is an anchor tag, you can simply use the href attribute value of the clicked link.
Delete
and in your js code
$("a.ajaxLink").click(function(e){
e.preventDefault();
var url = $(this).attr("href");
//use url variable value for the ajax call now.
});
If it is any other type of html element, you can use html5 data attribute to keep the target url and use the jQuery data method to retrieve it in your js code.
<div data-url="#Url.Action("Delete","Product")" class="ajaxLink">Delete</div>
and in your js code
$(".ajaxLink").click(function(e){
e.preventDefault(); // to be safe
var url = $(this).data("url");
//use url variable value for the ajax call now.
});
As you are using this in a js file you can do something like this:
$("#btnAnswer").click(function () {
var hostString = window.location.protocol + "//" + window.location.host + /";
$.ajax({
url: hostString + "/appName/Controller/method/",
//url: "/Controller/method/",
data: { answer: $("#answer").val(), question_id: $("#question_id").val(), answer_id: $("#answer_id").val() },
success: function (result) {
alert(result);
}
}).error(function () {
}).fail(function () {
});
});
Related
Trying to find a resource that could point me in the right direction for downloading a file with this particular stack. It's more challenging than it seems, especially since I'm unable to use Razor in accordance with house rules.
The code execution can get from the markup, to the knockout, and then the C#, but it doesn't start a download like I would expect in ordinary webforms non-MVC ASP.NET.
mark up:
<div class="row">
<div class="col-2"><img data-bind="attr: {src: image}, click: $root.downloadFile/></div>
the knockout/javascript call:
self.downloadFile = function(e){
if(e) {
attachmentId = e.id;
helpers.ajax.getJson(root, "/Files/DownloadFile/", {fileId: attachmentId }, function(x){
attachmentId=0;
getFiles();
});
}
...
related javascript functions called here:
helpers.ajax.getJson = function(path, url, data, onSuccess, onError){
helpers.ajax.async('GET', path, url, {
data: data,
cache: false,
async: true,
error: onError,
success: onSuccess
});
};
function getFiles(){
self.files([]);
helpers.ajax.getJson(root, "/Files/GetFiles",
{ profileId: self.ProfileId() },
function (files) {
if(files) {
$.each(files, function (i, v) {
self.files().push(new file(v.AttachmentId, v.FileTypeDescr, v.FileExtension, v.FileName, v.UploadedBy, v.UploadDate, v.CompletionDate));
self.files.valuehasMutated();
});
}
});
}
C#
public FileResult DownloadFile(int fileId)
{
ODSAPI.AttachmentFile file = FileFunctions.GetById(fileId);
if(file != null)
{
return File(file.FileData, file.ContentType);
}
return null;
}
this returns the correct file information and the bits from the database when I step through the code and view the file variable.
you could use http://danml.com/download.html to download file from javascript AJAX return
for exmaple
download(data, 'Export.csv', 'application/csv');
where data will be return from your ajax request and file name and file type.
The JSON call in the Javascript was incorrect as it called for a JSON object. Rather, it should have been:
window.open(root + "/Files/DownloadFile?fileId=" + attId, '_blank');
instead of helpers.ajax.getJson()
I have a HomeController in my ASP.NET MVC application in folder "Controllers". My View is in: "View/Home/Index.cshtml" (look at my figure below).
I am using Ajax to get some json file every a few second. Problem is in Ajax URL, because I really don't know and didn't find, how to tell that property, that it has to go back a few folders and then find the HomeController.
My Solution looks like this:
Here is a method in my HomeController:
[HttpGet]
public ActionResult GetRandomFeed()
{
Item i = ss.getRandomFeed();
return Json(new { Source = i.Media.Source, Avatar = i.User.Avatar, Text = i.Text, Name = i.User.Name }, JsonRequestBehavior.AllowGet);
}
My AJAX in the View:
setInterval(function () {
$.ajax({
type: "GET",
url: '/HomeController.cs/GetRandomFeed', // Of course I have tried a lots of attempts in here
contentType: "application/json;", // Not sure about this
dataType: "json",
success: function (response) {
console.log("Success :)");
},
error: function() {
console.log("Error!");
}
});
}, 2000);
All I want to get that JSON file (or can be even an array of strings) and use it in my Success function. It is a simple Slide Show and JSON contains the URLs that I want to show in the page every X seconds (just changing source of an image that is in that JSON file).
I couldn't find anything like this. How to use that URL correctly OR found something similiar for WebForms but cannot use it in MVC.
Change your AJAX URL declaration to:
url: '/Home/GetRandomFeed'
Remove the .cs
Or you can also do, assuming this view is under your controller:
url: '#Url.Action("GetRandomFeed")'
In my experience, it doesn't seem enter the function is just because the JSON return from the controller doesn't include Status = "OK"
[HttpGet]
public ActionResult GetRandomFeed()
{
...
...
return Json(new
{
Status = "Ok", ...
}
I have the following script tag included on the _layout page of my MVC application:
<script src="https://backpack.openbadges.org/issuer.js"></script>
This is used to issue badges on completion of courses. Thus far I have been issuing badges directly from the Views using javascript such as:
var postData = {
'badgeClassID': 1
};
$.ajax({
type: "GET",
cache: false,
url: "/Admin/NewBadgeAssertion",
data: postData,
success: function (dataBA) {
var myURL = dataBA;
OpenBadges.issue([myURL]);
},
error: function (error) {
alert("An Error has occurred during the Issue of this OpenBadge");
}
});
This is working for elearning courses that I have created but the completion of SCORM courses are recorded on close of the window and I now want to issue badges for SCORM courses through C# code behind rather than from the browser view.
How can I call OpenBadges.issue([myURL]) from code behind using ClientScriptManager. I have found the RegisterStartupScript method but I am not sure how to derive the type, key and script values. I have tried this:
ClientScriptManager csm = new ClientScriptManager();
csm.RegisterStartupScript(GetType(), "msgbox", "alert('SCORM BADGE HAS BEEN ISSUED FOR SUCCESSFUL COMPLETION');", true);
But I am not correctly defining any constructors
Try this:
First, on your view page, create a simple javascript function, which does what you need it to do, such as call OpenIssues.issue:
function myFunction(myUrl)
{
alert('test:' + myUrl);
OpenBadges.issue(myUrl);
}
And in your codebehind, you can call the javascript function:
String jscript = "myFunction('" + myUrl + "')"; //sending url as parameter
Page.ClientScript.RegisterStartupScript(this.GetType(),"myscript",jscript,true);
I have an action in a MobileController called 'myaction' and I call it with javascript like so:
<script type="text/javascript">
function SubmitData() {
$.ajax(
{
type: "POST",
url: "http://localhost:1613/Mobile/myaction",
data: "id to post",
success:
function (result) {
window.alert("SUCCESS");
},
error: function (req, status, error) {
window.alert("ERROR!");
}
}
);
}
</script>
Notice however the url is not using relative paths, I tried making it just ~/Mobile/myaction but that didn't work.
Any ideas how I can make it so the url being pointed to will work in all cases and not just if the domain is localhost:1613? Like if I uploaded it to mysite.com it would find the action at mysite.com/mobile/myaction.
Thanks for any help!
Have you tried:
url: "#Url.Action(....)",
Replace the url by:
url: "/Mobile/myaction"
With ~ sign, it will only work with server controls/functions.
url: "#Url.Content("~/appName/Mobile/myaction/")"
Html::"/appName/Mobile/myaction/"I suggest you to give your app Virtual path "/appName" doing this i'll allow you to avoid appName in url
You can use something like this:
new UrlHelper( HttpContext.Current.Request.RequestContext ).Action( "<action>", "<controller>", new { id = 1 } )
I'm using this exactly to pass values to a javascript function
I have a problem with a master page containing a asp:textbox that I'm trying to access using jQuery. I have read lot sof thread regarding this and tried all the different approaches I have seen, but regardless, the end result end up as Undefined.
This is the relevant part of the MasterPage code:
<p><asp:Label ID="Label1" AssociatedControlID="osxinputfrom" runat="server">Navn</asp:Label><asp:TextBox CssClass="osxinputform" ID="osxinputfrom" runat="server"></asp:TextBox></p>
When I click the button, the following code from a jQuery .js file is run:
show: function(d) {
$('#osx-modal-content .osxsubmitbutton').click(function (e) {
e.preventDefault();
if (OSX.validate()){
$('#osx-modal-data').fadeOut(200);
d.container.animate(
{height:80},
500,
function () {
$('#osx-modal-data').html("<h2>Sender...</h2>").fadeIn(250, function () {
$.ajax({
type: "POST",
url: "Default.aspx/GetDate",
data: "{'from':'" + $("#osxinputfrom").val() + "','mailaddress':'" + $("#osxinputmail").val() + "','header':'Test3','message':'Test4'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$('#osx-modal-data').fadeOut(200, function () {
$('#osx-modal-data').html('<h2>Meldingen er sendt!</h2>');
$('#osx-modal-data').fadeIn(200);
});
},
error: function(msg){
$('#osx-modal-data').fadeOut(200, function () {
$('#osx-modal-data').html('<h2>Feil oppstod ved sending av melding!</h2>');
$('#osx-modal-data').fadeIn(200);
});
}
});
});
}
);
}
else{
$('#osxinputstatus').fadeOut(250, function () {
$('#osxinputstatus').html('<p id="osxinputstatus">' + OSX.message + '</a>');
$('#osxinputstatus').fadeIn(250);
});
}
});
},
So the problem here is that $("#osxinputfrom").val() evaluated to Undefined. I understand that the masterpage will add some prefix to the ID, so I tried using the ID from the page when it's run that ends up as ct100_osxinputfrom, and I also tried some other hinds that I found while searching like $("#<%=osxinputfrom.ClientID%>"), but it ends up as Undefined in the method that is called from the jQuery ajax method anyway. The third and fourth parameters to the ajay function that is hardcoded as Test3 and Test4 comes fine in the C# backend method.
So my question is simply: How can I rewrite the jQuery selector to fetch the correct value from the textbox? (before I used master pages it worked fine by the way)
Best regards
Daemon
It will be abit slower but why dont you try adding cssclass="bla" to your label and then get it with $('.bla').val(); ?
You should use the attribute ends with selector
Link
it would be $("id$='osxinputfrom'")