Is it possible to add some headers, before sending a request to GET action ?
What I want to do, is to specify headers like:
-Accept application/json
-Content-Type application/json
...
before entering a GET method in my controller.
If you are using HttpClient sending a GET request with Accept and Content-Type headers would look something like this:
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUri)
{
Content = content,
};
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
HttpResponseMessage response = await client.SendAsync(request);
Keep in mind that the code uses the Async version of sending the request, so you have to decorate your method with the "Async" keyword in order for this to work.
If you want to send the request from the front-end you should use ajax and your code would look something like this:
$.ajax({
url: 'URL HERE',
type: 'GET',
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (data) {
// here goes the data that came from the response..
}
});
How about this?
$.ajax({
url: '#Url.Action("GetData", "Home")',
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (result) {
}
});
Controller
public ActionResult GetData()
{
return Json("What I want to send", JsonRequestBehavior.AllowGet);
}
Related
I'm new to .NET MVC. I'm trying to make an Ajax call to a .NET method, but it doesn't work. Please help.
Here is my Ajax code:
function resendConfirmationEmail()
{
$("#resend-confirmation-email-status").html('<img src="../../Content/img/ajax-loader.gif" />');
$.ajax({
url: "/Ultility/ResendConfirmationEmail",
type: "POST",
datatype: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ "userID": $('#confirmation-email-userid').text().toString(), "subject": $('#confirmation-email-subject').text().toString() }),
async: true,
processData: true,
cache: false,
success: function (data) {
$("#resend-confirmation-email-status").html("Email sent");
}
});
}
And here is my .Net method in UtilityController:
[HttpPost]
[WebMethod]
public JsonResult ResendConfirmationEmail(string userID, string subject)
{
string destination = db.Users.Where(u => u.Id == userID).Select(u => u.Email).FirstOrDefault();
Task<string> result = new AccountController().SendEmailConfirmationTokenAsync(userID, subject, destination);
return Json(result, JsonRequestBehavior.DenyGet);
}
Try removing the quotation marks in the data parameters of the ajax request
Like this:
function resendConfirmationEmail()
{
$("#resend-confirmation-email-status").html('<img src="../../Content/img/ajax-loader.gif" />');
$.ajax({
url: "/Ultility/ResendConfirmationEmail",
type: "POST",
datatype: "json",
contentType: "application/json; charset=utf-8",
data:
JSON.stringify({
userID: $('#confirmation-email-userid').text().toString(),
subject: $('#confirmation-email-subject').text().toString()
}),
async: true,
processData: true,
cache: false,
success: function (data) {
$("#resend-confirmation-email-status").html("Email sent");
}
});
}
Try this, but if you using asp.net mvc, i guess you don't need [WebMethod] attribute
[HttpPost]
[WebMethod]
public JsonResult ResendConfirmationEmail([FromBody] MyModel model)
{
....
}
public class MyModel{
public string userID {get; set;}
public string string subject {get; set;}
}
I think issue with your url where in
use "url: "/Ultility/ResendConfirmationEmail","
insted of "url: "/Utility/ResendConfirmationEmail","
because your controller name is UtilityController
Do not use Webmethod in .net method
No need to use JSON.Stringify in ajax
function resendConfirmationEmail()
{
$("#resend-confirmation-email-status").html('<img src="../../Content/img/ajax-loader.gif" />');
$.ajax({
url: "/Ultility/ResendConfirmationEmail",
type: "POST",
datatype: "json",
contentType: "application/json; charset=utf-8",
data: "{'userID': "+$('#confirmation-email-userid').text().toString()+",'subject': "+$('#confirmation-email-subject').text().toString()+" }",
async: true,
processData: true,
cache: false,
success: function (data) {
$("#resend-confirmation-email-status").html("Email sent");
}
});
}
Remove the [webmothod] data annotation from your action method,
second option you are trying to pass json object for that u dont need to convert into string. Simply pass object
It wil work 👍
I need to call a web api, this web api method is accepting two parameter one is enum type and another is int. I need to call this api using Ajax Jquery. How to pass enum paramter.
API Code
[HttpGet]
public HttpResponseMessage GetActivitiesByType(UnifiedActivityType type, int pageNumber)
{
var activities = _activityService.GetAllByType(type, pageNumber);
return Request.CreateResponse(HttpStatusCode.OK, activities);
}
My Ajax Call Code:
var jsonData = { 'type': 'Recommendation', pageNumber: 0 };
$.ajax({
type: 'get',
dataType: 'json',
crossDomain: true,
url: CharismaSystem.globaldata.RemoteURL_ActivityGetAllByType,
contentType: "application/json; charset=utf-8",
data: jsonData,
headers: { "authorization": token },
error: function (xhr) {
alert(xhr.responseText);
},
success: function (data) {
alert('scuess');
}
});
Any Suggestions..
An enum is treated as a 0-based integer, so change:
var jsonData = { 'type': 'Recommendation', pageNumber: 0 };
To this:
var jsonData = { 'type': 0, pageNumber: 0 };
The client needs to know the index numbers. You could hard code them, or send them down in the page using #Html.Raw(...), or make them available in another ajax call.
You can not pass enum from client side. Either pass string or int and on the server side cast that value to enum. Something like,
MessagingProperties result;
string none = "None";
result = (MessagingProperties)Enum.Parse(typeof(MessagingProperties), none);
Or you can do something similar to this post
I have this ajax:
function sendData() {
var question = (document.getElementById('question').value).toString();
var c = (document.getElementById('c').value).toString();
$.ajax({
url: '/Home/InsertData',
type: 'POST',
data: {question:question, c:c},
// data: {},
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function () {
alert('suc');
},
error: function (error) {
alert('error');
}
});
}
in my HomeController, I have the function:
[HttpPost]
public void InsertData(string question, string c)
//public void InsertData()
{
this.insertDataToCustomers(question, c);
}
when I run it, I got an error of:
POST http://localhost:2124/Home/InsertData 500 (Internal Server Error)
If I didn't ask for input values in InsertData function and didn't send data in the ajax, it works. why can't I send data to InsertData function?
p.s. There are values in question and c
thank you!
Remove this:
contentType: 'application/json; charset=utf-8',
You are not sending any JSON to the server, so this is an incorrect content type for the request. You are sending a application/x-www-form-urlencoded request.
So:
function sendData() {
var question = $('#question').val();
var c = $('#c').val();
$.ajax({
url: '/Home/InsertData',
type: 'POST',
data: { question: question, c: c },
success: function () {
alert('suc');
},
error: function (error) {
alert('error');
}
});
}
Another problem with your code is that you indicated dataType: 'json' which means that you expect the server to return JSON but your controller action doesn't return anything. It's just a void method. In ASP.NET MVC controller actions should return ActionResults. So if you want to return some JSON for example to indicate the status of the operation you could have this:
[HttpPost]
public ActionResult InsertData(string question, string c)
{
this.insertDataToCustomers(question, c);
return Json(new { success = true });
}
Of course you could return an arbitrary object which will be JSON serialized and you will be able to access it in your success AJAX callback.
In MVC, I have written an action in the controller for getting values. The action is as follows..
public void poolshapepdf(List<String> values)
{
...
}
To pass the parameter values to the controller action i pass the values from javascript..
the code is the below,
$.ajax({
type: 'POST',
url: rootDir + "IngroundCalculation/poolshapepdf",
data: { values: collectionPSElmt },
traditional: true,
});
Here collectionPSElmt is an array.
collectionPSElmt[index] = poolshapeValue[index] + "-" + psFeet[index] + "-" + psInch[index];
Here the issue is the controller action cannot be called from the javascript $.Ajax(..).
How do I fix this issue?
You calling the controller by POST and JSON data:
[HttpPost]
public JsonResult poolshapepdf(DataClass[] items)
{
}
Now, make a proper call to your url.
specify the data type as json and always go for success function.
using that you can easily crack the report.
$.ajax({
url: '#Url.Action("poolshapepdf", "IngroundCalculation")',
type: "POST",
dataType: 'json',
data: collectionPSElmt ,
contentType: "application/json; charset=utf-8",
success: function (result) {
alert("Working..");
}
});
And at Controller Side,
[HttpPost]
public JsonResult poolshapepdf(DataClass[] items)
{
// Your Code here....
}
I use $.ajax() to poll an action method every 5 seconds as follows:
$.ajax({
type: 'GET', url: '/MyController/IsReady/1',
dataType: 'json', success: function (xhr_data) {
if (xhr_data.active == 'pending') {
setTimeout(function () { ajaxRequest(); }, 5000);
}
}
});
and the ActionResult action:
public ActionResult IsReady(int id)
{
if(true)
{
return RedirectToAction("AnotherAction");
}
return Json("pending");
}
I had to change the action return type to ActionResult in order to use RedirectToAction (originally it was JsonResult and I was returning Json(new { active = 'active' };), but it looks to have trouble redirecting and rendering the new View from within the $.ajax() success callback. I need to redirect to "AnotherAction" from within this polling ajax postback. Firebug's response is the View from "AnotherAction", but it's not rendering.
You need to consume the result of your ajax request and use that to run javascript to manually update window.location yourself. For example, something like:
// Your ajax callback:
function(result) {
if (result.redirectUrl != null) {
window.location = result.redirectUrl;
}
}
Where "result" is the argument passed to you by jQuery's ajax method after completion of the ajax request. (And to generate the URL itself, use UrlHelper.GenerateUrl, which is an MVC helper that creates URLs based off of actions/controllers/etc.)
I know this is a super old article but after scouring the web this was still the top answer on Google, and I ended up using a different solution. If you want to use a pure RedirectToAction this works as well. The RedirectToAction response contains the complete markup for the view.
C#:
return RedirectToAction("Action", "Controller", new { myRouteValue = foo});
JS:
$.ajax({
type: "POST",
url: "./PostController/PostAction",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
complete: function (result) {
if (result.responseText) {
$('body').html(result.responseText);
}
}
});
C# worked well
I just changed the JS because responseText was not working for me:
$.ajax({
type: "POST",
url: posturl,
contentType: false,
processData: false,
async: false,
data: requestjson,
success: function(result) {
if (result) {
$('body').html(result);
}
},
error: function (xhr, status, p3, p4){
var err = "Error " + " " + status + " " + p3 + " " + p4;
if (xhr.responseText && xhr.responseText[0] == "{")
err = JSON.parse(xhr.responseText).Message;
console.log(err);
}
});
You could use the Html.RenderAction helper in a View:
public ActionResult IsReady(int id)
{
if(true)
{
ViewBag.Action = "AnotherAction";
return PartialView("_AjaxRedirect");
}
return Json("pending");
}
And in the "_AjaxRedirect" partial view:
#{
string action = ViewBag.ActionName;
Html.RenderAction(action);
}
Reference:
https://stackoverflow.com/a/49137153/150342