Home @Url.Action not working on AJAX call
Reply: 1

@Url.Action not working on AJAX call

TheFallenOne
1#
TheFallenOne Published in 2018-02-11 22:26:49Z

This question already has an answer here:

  • .JS File using @url.action in Ajax Url 1 answer

I am trying to use AJAX to post a set of values from my view to my controller. However instead of converting the URL.Action into corresponding controller and action., it is appearing as url.action in the URL.

This is my code :

$('#addBtn').click(function() {
var patientId = $("#txtPatientId").val();

$.ajax({
    cache : false,
    url: '@Url.Action("AddPatient","Home")',
    type: 'POST',
    data: {patientId: patientId},
    }).done({});
});

Controller:

[HttpPost]
public ActionResult AddPatient(string patientId)
{

}

The URL I see in the network tab gives me a 404 errror as it is trying to access the URL localhost/@Url.Action("AddPatient","Home").

Am I missing something?

RAHUL S R
2#
RAHUL S R Reply to 2018-02-12 05:17:27Z

so as the comment says you cannot use razor codess outside the cshtml file ie in an external js file

you have two choices here

1 try static url

$.ajax({
    cache : false,
    url: '/Home/AddPatient'
    type: 'POST',
    data: {patientId: patientId},
    }).done({});
});

2 save the url in a global var in cshtml file then read it in external js file catch make sure you refer the file after the global var is decleared and nitialized

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.326496 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO