Ajax and ASP.NET MVC- Get page URL, not the controller/action URL - ajax

I have an Ajax method that calls an MVC action from a controller class.
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "/ajax/Updates/Message",
dataType: "json",
success: function (response) {
//data variable has been declared already
data = response;
},
complete: function () {
if (data !== "") {
$('#div1').text(window.location.path);
$('#div2').text(data);
}
},
});
[HttpGet]
public async Task < ActionResult > Message()
{
string d = "test string";
return Json(d, JsonRequestBehavior.AllowGet);
}
The 'url' within the Ajax method is the call to the action method.
What to do if I want to return the actual page URL in Ajax Response, not the controller/action url?
So this controller does not have a view or anything associated with it, it is more like a helper class. When I am using ajax in any of the other pages, it is not returning the URL path of that specific page (via 'window.location.path) e.g. /Accounts/Summary , rather it is returning Updates/Message (in reference to the controller and action)

The web is stateless, when you call Updates/Message with ajax, it doesn't know it's for page Accounts/Summary. You'll have to pass this as parameter (post or get) or you could try Request.UrlReferrer which should contain the url of the page that called the request.

I hope this will help you try this code:
ajax code
$.ajax({
type: 'GET',
url: '#Url.action("Message","Updates")', // url.action(ActionName,ControllerName)
success: function (data) {
window.location = data;
},
error: function (xhr) { // if error occured
alert("Error occured.please try again");
}
dataType: 'json'
});
actionresult :
[HttpGet]
public async Task<ActionResult> Message()
{
string d = "http://www.google.com";
return Json(d, JsonRequestBehavior.AllowGet);
}

Related

ASP.NET MVC controller won't receive my ajax get method data

Here's a function that calls an ajax get method:
function getSubProjName(projectId) {
console.log(projectId)
var projectName = "";
//ajax get request to get the subproject name
$.ajax({
type: 'GET',
url: '#Url.Action("GetSubProjName", "Home")',
data: { projectId: projectId },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
console.log(response);
projectName = response;
},
error: function (response) {
console.log(response);
}
});
return projectName;
}
I've checked it a billion times, projectId most definitely receives a value. If it helps, its always a numerical value.
Then I have a method in my controller that SHOULD receive the projectId and do something with it:
[HttpGet]
public JsonResult GetSubProjName([FromBody] string projectId)
{
// some code here
return Json(""); //return the code results back to the view
}
My problem is that I just can't get the controller to actually receive the data from the ajax call. All I get in my string ProjectId, in my controller method, is always null.

Is there any way to get data type of XMLHttpRequest on base controller in .net core 3.1

Here is any Jquery ajax POST request;
$.ajax({
type: "POST",
url: "/Customers/GetAll",
contentType: "application/json",
dataType: "json",
success: function(response) {
console.log(response);
},
error: function(response) {
console.log(response);
}
});
Here is my Controller Action Method which requested by ajax above;
public IActionResult GetAll()
{
//Method body...
}
How can I get the dataType of any ajax request in base controller or action method?
Try to get accept in headers:
action:
public IActionResult GetAll()
{
string dataType = HttpContext.Request.Headers["accept"].ToString();
//Method body...
}
The headers can be retrieved on the HttpContext object.
if(HttpContext.Request.Headers.TryGetValue("accept", out var acceptHeaders)) {
var firstAcceptHeader = acceptHeaders.FirstOrDefault();
}
You can also access the header value using indexing Headers["accept"], but be aware, that if there is no accept header, for whatever reason, this will throw a NullReferenceException.

Unable to 'call' controller action from ajax post

I'm using net.core for the first time today and I'm trying to call an action method from an ajax call:
My Ajax call (from a normal HTML page)
$("#contactMap").click(function (e) {
e.preventDefault();
var url = "/MapObjects/mapContact";
//I've tried MapObjectsController & '#Url.Action("mapContact", 'MapObjects")'; But to no avail
$.ajax({
url: url,
type: 'POST',
contentType: 'application/json; charset=utf-8',
cache: false,
success: function (result) {
alert("success");
}
});
});
And in my controller:
namespace myName.Controllers
{
public class MapObjectsController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult mapContact()
{
Account account = new Account();
return Json(account);
}
}
}
The 'account' is just a normal model (obvs empty in this case). All I receive is a 404 error in the console though.
As mentioned this is the 1st time I've .net Core (this is code I've written loads of times in 'normal' MVC projects) so it's possible that I'm missing something really obvious.
Thanks,
C
The first, try to call the #Url.Action() explicitly in the Ajax call :
$("#contactMap").click(function (e) {
e.preventDefault();
$.ajax({
url: '#Url.Action("mapContact", "MapObjects")',
type: 'POST',
contentType: 'application/json; charset=utf-8',
cache: false,
success: function (result) {
alert("success");
}
});
});
The second, check your routing rules.

Render partial view with AJAX-call to MVC-action

I have this AJAX in my code:
$(".dogname").click(function () {
var id = $(this).attr("data-id");
alert(id);
$.ajax({
url: '/Home/GetSingleDog',
dataType: 'html',
data: {
dogid: id,
},
success: function (data) {
$('#hidden').html(data);
}
});
});
The alert gets triggered with the correct value but the AJAX-call does not start(the method does not get called).
Here is the method that im trying to hit:
public ActionResult GetSingleDog(int dogid)
{
var model = _ef.SingleDog(dogid);
if (Request.IsAjaxRequest())
{
return PartialView("_dogpartial", model);
}
else
{
return null;
}
}
Can someone see what i am missing? Thanks!
do you know what error does this ajax call throws?
Use fiddler or some other tool to verify response from the server.
try modifying your ajax call as following
$.ajax({
url: '/Home/GetSingleDog',
dataType: 'string',
data: {
dogid: id,
},
success: function (data) {
$('#hidden').html(data);
}
error: function(x,h,r)
{
//Verify error
}
});
Also try
$.get("Home/GetSingleDog",{dogid : id},function(data){
$('#hidden').html(data);
});
Make sure, URL is correct and parameter dogid(case sensitive) is same as in controller's action method

can't get to web api controller action with jquery ajax post

I'm trying to create my first REST application with the web api in mvc4. I have a controller set up with the HttpPost verb but for some reason when I click the link to post the xml string to the controller I get an error - "{"Message":"No HTTP resource was found that matches the request URI '/api/Apply/ApplyToJob'.","MessageDetail":"No action was found on the controller 'Apply' that matches the request."}" Any ideas what I might be doing wrong? Here's the view page...
Post Data
<script type="text/javascript">
window.onload = function () {
$("#lnkPost").on("click", function () {
$.get("/TestResponse.xml", function (d) {
$.ajax({
//contentType: "text/xml",
//dataType: "xml",
type: "post",
url: "/api/Apply/ApplyToJob",
data: {
"strXml": (new XMLSerializer()).serializeToString(d)
},
success: function () { console.log('success'); }
});
});
});
};
</script>
and here's the controller.
public class ApplyController : ApiController
{
[HttpPost]
[ActionName("ApplyToJob")]
public string ApplyToJob(string strXml)
{
return "success";
}
}
Modify your action's parameter like below:
public string ApplyToJob([FromBody]string strXml)
This is because without this FromBody attribute, the string parameter is expected to come from the Uri. Since you do not have it in the Uri the action selection is failing.
Also, looking at your client code, shouldn't you set the appropriate content type header in your request?
Edited:
You can modify your javascript to like below and see if it works:
$.ajax({ contentType: "text/xml",
dataType: "xml",
type: "post",
url: "/api/values",
data: "your raw xml data here",
success: function () { console.log('success'); }
});

Resources