Getting link to an action? - c#

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

Related

absolute path on call ajax mvc4 c#

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 () {
});
});

Ajax post not working MVC 5

I'm trying to post data into a controller but it doesn't seems to work, I need the post to include the content of the view into a div when done but I cant quite achieve it
Here's my js function:
function show(num) {
$.ajax({
dataType: "html",
type: "POST",
url: "Student/Schedule",
data: { number: num },
success: function (a) {
// Replace the div's content with the page method's return.
alert("success");
$('#schedule').load(a);
}
});
}
And, here's my controller:
public ActionResult Schedule(String number)
{
return View(number);
}
I am a noob in MVC and C#, so any help is welcome.
There are somethings that you should fix to solve the problem.
Change Url to "/Student/Schedule"
You are using "Student/Schedule" as url, so you are trying to call an action named "Student".
Add [HttpPost] to your action.
You should return PartialView("Schedule", number);.
When you use return View(number) it uses the string value of number as your view name. You should explicitly pass view name and model.
Use $('#schedule').html(a);
It's better to add an error function to your ajax call to be able to find errors:
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
//or you can put jqXHR.responseText somewhere as complete response. Its html.
}
Your action should return a Partial View, not a View.
Change your action to:
[HttpPost]
// by the way use string instead of String
public ActionResult Schedule(string number)
{
return PartialView("_Schedule", number);
}
Then, you'll need to create a partial view named _Schedule.cshtml.
Also, you need to change $('#schedule').load(a); to $('#schedule').html(a); And, I'd suggest that you use a Url.Action to set your url in your ajax call, like this:
function show(num) {
$.ajax({
dataType: "html",
type: "POST",
url: '#Url.Action("Schedule", "Student")',
data: { number: num },
success: function (a) {
// Replace the div's content with the page method's return.
alert("success");
$('#schedule').html(a);
}
});
}
I had the same issue what i did was adding jquery.unobtrusive-ajax.js to my scripts

Ajax/Json post to aspx page results in 404 error

I'm trying to do an ajax post to c#. When I do the post though, it results in a 404 error. Here's my code:
Javascript:
var submitParams = {
'companyName': $("#company_name").val(),
'companyAddress1': $("#company_address_1").val()
};
$.ajax({
type: "POST",
url: "ClientManagement.aspx/Submit",
dataType: "json",
contentType: "application/json; charset=utf-8",
async: true,
data: JSON.stringify({ submitParams }),
success: function () {
alert("hi");
$(this).dialog("close");
},
error: function (e) {
debugger;
}
});
c# code:
[WebMethod]
public static void Submit(object parameters)
{
string name = parameters.ToString();
}
So it can't find my ClientManagement.aspx/Submit method. It jumps straight into my "error" function. Also, this is being performed on a regular aspx page.
Any idea what I'm doing wrong?
Could it be as simple as
url: "/ClientManagement.aspx/Submit"
?
Usually, ASP.NET Web Services have a .asmx file extension. If that does not work, try using the fully qualified domain name of the web service.
After a day of trying to resolve this, I came to the head shaking realization that I misspelled my page name. In my ajax post, I'm calling ClientManagement.aspx. My real page was misspelled as ClientManagment.aspx (missing the 'e').
Thanks for your help.

ajax call to c# mvc sends both post and get

I've looked at several solutions for making an ajax call and by not this issue mentioned anywhere i feel it might be something specific to the environment i'm working with.
My controller:
[HttpPost]
public ActionResult ChangeDefualtCC(string a)
{
return Json("ok");
}
[HttpGet]
public ActionResult ChangeDefualtCC()
{
return Json("ok");
}
JS:
$("nevermind").change(function () {
$.ajax({
type: "POST",
url: "/Account/ChangeDefualtCC",
dataType: "json",
data: {
a: "A"
},
success: function (data) { console.log(data)},
error: function (data) { console.log("error");}
});
});
The Controller code is never hit, and this is what i'm seeing in chrome after the ajax call:
EDIT 2: The page hits the [HttpGet] method.
EDIT:
I tagged Ektron as well because it is used in the project, and it is possible that it is affecting the call.
My Routes:
Update: I have tried using Get, as well as Post, and also returning back to the View I was in, I get the 302 everytime.
any ideas?
It looks like it finds the "get" because you don't have a parameter in that call. I think you might be missing the content type from your ajax call, so the model binder cannot parse the content of your post as a parameter.
$.ajax({
type: "POST",
url: "/Account/ChangeDefualtCC",
contentType: 'application/json; charset=utf-8',
dataType: "json",
data: {
a: "A"
},
success: function (data) { console.log(data)},
error: function (data) { console.log("error");}
});
Your code seems to be absolutely correct.
This not be exact solution but try this may it work.
$("nevermind").change(function () {
$.post("/../Home/ChangeDefualtCC", { a: "A" }, function (data) {
console.log(data)
});
});
Our project is integrated with the CMS Ektron. We later discovered that Ektron is hit before the C# code, and has some affect to any url without a trailing url.
Thanks for all the help

Calling a C# method with jquery

I am trying to call a method with jQuery on a button click.This is waht I have so far:
$("a.AddToCart").click(function () {
var link = document.URL;
$.ajax({
type:"POST",
url: "/Account/AddToCartHack",
data: {url : link},
contentType: "application/json; charset=utf-8",
dataType: "json"
});
});
[WebMethod]
public void AddToCartHack(string url)
{
GeneralHelperClass.URL = url;
}
What I am trying to do here is when I click the link with class add to cart I want to call the method AddToCartHack and pass it the curent URL as a parameter.
I must be doing something wrong because it seems that AddToCartHack is not being called.
What am I doing wrong?
There are quite a lot of issues with your code, I don't know where to start. So let's conduct an interactive refactoring session with you (if you don't care about my comments but just want to see the final and recommended solution, just scroll down at the end of answer).
First: you don't seem to be canceling the default action of the anchor by returning false from the .click() event handler. By not doing this you are actually leaving the browser perform the default action of the anchor (which as you know for an anchor is to redirect to the url that it's href attribute is pointing to. As a consequence to this your AJAX call never has the time to execute because the browser has already left the page and no more scripts are ever running). So return false from the handler to give your AJAX script the possibility to execute and stay on the same page:
$("a.AddToCart").click(function () {
var link = document.URL;
$.ajax({
type:"POST",
url: "/Account/AddToCartHack",
data: {url : link},
contentType: "application/json; charset=utf-8",
dataType: "json"
});
return false;
});
Second: You have specified contentType: 'application/json' request header but you are not sending any JSON at all. You are sending a application/x-www-form-urlencoded request which is the default for jQuery. So get rid of this meaningless parameter in your case:
$("a.AddToCart").click(function () {
var link = document.URL;
$.ajax({
type:"POST",
url: "/Account/AddToCartHack",
data: {url : link},
dataType: "json"
});
return false;
});
Third: You have specified that your server side code will return JSON (dataType: 'json') but your server side code doesn't return anything at all. It's a void method. In ASP.NET MVC what you call C# method has a name. It's called a controller action. And in ASP.NET MVC controller actions return ActionResults, not void. So fix your contoller action. Also get rid of the [WebMethod] attribute - that's no longer to be used in ASP.NET MVC
public class AccountController: Controller
{
public ActionResult AddToCartHack(string url)
{
GeneralHelperClass.URL = url;
return Json(new { success = true });
}
}
Fourth: you have hardcoded the url to the controller action in your javascript instead of using server side helpers to generate this url. The problem with this is that your code will break if you deploy your application in IIS in a virtual directory. And not only that - if you decide to modify the pattern of your routes in Global.asax you will have to modify all your scripts because the url will no longer be {controller}/{action}. The approach I would recommend you to solve this problem is to use unobtrusive AJAX. So you would simply generate the anchor using an HTML helper:
#Html.ActionLink(
"Add to cart",
"AddToCartHack",
"Account",
null,
new { #class = "AddToCart" }
)
and then unobtrusively AJAXify this anchor:
$('a.AddToCart').click(function () {
var link = document.URL;
$.ajax({
type: 'POST',
url: this.href,
data: { url : link }
});
return false;
});
Fifth: You seem to be employing some document.URL variable inside your .click() handler. It looks like some global javascript variable that must have been defined elsewhere. Unfortunately you haven't shown the part of the code where this variable is defined, nor why is it used, so I cannot really propose a better way to do this, but I really feel that there's something wrong with it. Or oh wait, is this supposed to be the current browser url??? Is so you should use the window.location.href property. Just like that:
$('a.AddToCart').click(function () {
$.ajax({
type: 'POST',
url: this.href,
data: { url : window.location.href }
});
return false;
});
or even better, make it part of the original anchor (Final and recommended solution):
#Html.ActionLink(
"Add to cart",
"AddToCartHack",
"Account",
new { url = Request.RawUrl },
new { #class = "AddToCart" }
)
and then simply:
$('a.AddToCart').click(function () {
$.ajax({
type: 'POST',
url: this.href
});
return false;
});
Now that's much better compared to what we had initially. Your application will now work even with javascript disabled on the page.
place script method this way as shown below
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
Add Success and error function to check your ajax functionality
...
$.ajax({
type:"POST",
url: "/Account/AddToCartHack",
data: {url : link},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(){
alert('success');
},
error:function(){
alert('error');
}
});
....
If this is Asp.Net webforms you will need to make the webmethod static or the method cannot be accessed through JavaScript.
$(document).ready(function () {
$.ajax({
url: "Testajax.aspx/GetDate",
data: "f=GetDate",
cache: false,
success: function (content) {
$('#tableData').append('My Dear Friend');
alert(content);
},
failure: function (response) {
alert("no data found");
}
});
});

Categories

Resources