Method called a GET instead of POST - asp.net-web-api

I have this 'POST' method
[HttpPost]
[System.Web.Mvc.ValidateAntiForgeryToken]
public HttpResponseMessage UpdateProfile(string sAppUser)
{
MobileProfileModel profileModel= JsonConvert.DeserializeObject<MobileProfileModel>(sAppUser);
using (ucApp = new UserControllerApplication())
{
//this code should match the
bool success = ucApp.UpdateUserProfile(profileModel);
var response = Request.CreateResponse<bool>(HttpStatusCode.Created, success);
string uri = Url.Link("DefaultApi", new { result = success });
response.Headers.Location = new Uri(uri);
return response;
}
}
and i calling it like this AJAX 'POST'
$.ajax({
url: "http://mydomain.com/api/User/UpdateProfile",
data:JSON.stringify(profile),
type: 'POST',
contentType: 'application/json',
//dataType: "json",
async: false,
cache: false,
success: function (data) {
$.blockUI({ message: "Success" });
},
error: function (xhr) {
alert(xhr.responseText);
},
beforeSend: function() {
$.blockUI({ message: $("#ajaxLoader") });
},
complete: function() {
$.unblockUI();
}
});
and im getting this error
<Error>
<Message>
The requested resource does not support http method 'GET'.
</Message>
</Error>
The problem is Im not calling a GET method and the method isnt marked as a GET either. I am not sure what the issue is.
UPDATE
these are my route definitions
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//specific route for just the public views
routes.MapRoute(
"publicview",
"publicview/details/{userName}",
new { controller = "publicview", action = "details", username = UrlParameter.Optional }
);
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
I am executing a Get method on the same controller and it works, this actually the post of that initial get.

There are two things here, firstly is there any reason why you have used full path in your ajax request and not absolute path ? Is this only for example purpose ? I would recommend you to you absolute path.
Next if you could try this in your ajax call, change the following
url: "http://mydomain.com/api/User/UpdateProfile",
to
url: "/api/User/UpdateProfile/" + profile,
Or else if you want to use the data: attribute in your ajax call use like this
data: {sAppUser: profile},
Let me know if this doesnt help.

i think there 2 are reasons for this error msessage:
your server uri routing routes your request to the wrong method
your ajax request are calling the wrong uri
if you want to be sure for calling POST look take a look via wireshark or try a different tool for post (e.g. curl)
UPDATE
your uri form AJAX reqeust is:
/api/User/UpdateProfile
your uri template is:
api/{controller}/{action}/{id}
I think you get this error because they don't match.
by the way: you should not use post for updating a profile, use PUT with an ID
for example:
$.ajax({
url: "/api/User/UpdateProfile/"+UserID,
data:JSON.stringify(profile),
type: 'PUT',
contentType: 'application/json',
//dataType: "json",
async: false,
cache: false,
success: function (data) {
$.blockUI({ message: "Success" });
},
error: function (xhr) {
alert(xhr.responseText);
},
beforeSend: function() {
$.blockUI({ message: $("#ajaxLoader") });
},
complete: function() {
$.unblockUI();
}
});
and in the controller:
[HttpPut]
[System.Web.Mvc.ValidateAntiForgeryToken]
public HttpResponseMessage UpdateProfile(string sAppUser) // I don't know how to parse the id from uri ;)
{
//find the user by his uniqe ID
MobileProfileModel profileModel= JsonConvert.DeserializeObject<MobileProfileModel>(sAppUser);
using (ucApp = new UserControllerApplication())
{
//this code should match the
bool success = ucApp.UpdateUserProfile(profileModel);
var response = Request.CreateResponse<bool>(HttpStatusCode.Created, success);
string uri = Url.Link("DefaultApi", new { result = success });
response.Headers.Location = new Uri(uri);
return response;
}
}

Related

Passing ID to Controller using Ajax - Error 404 in Laravel

I am new to Laravel.
Trying to Pass ID from View to Controller but getting Error
POST http://127.0.0.1:8000/getbuffaloidformonitor 404 (Not Found)
This is my View BuffaloMonitor :
$(document).on('click', '.viewmonitormodal', function() {
var modal_data = $(this).data('info').split(',');
$('#viewbuffaloID').val(modal_data[1]);
var buffaloid = document.getElementById('viewbuffaloID').value// get buffalo id from textbox to get data for that ID
alert(buffaloid);
//alert(data);
$(function() {
$.ajax({
method : "POST",
url: "/getbuffaloidformonitor",
data: {
'_token': $('input[name=_token]').val(),
'id': buffaloid,
},
success : function(response) {
alert(response);
}
});
});
}
This is BuffalomonitorCOntroller :
public function getbuffaloidformonitor(Request $req) {
$data = buffalodata::find($req->id);
alert(data);
$id = $req('data');
return $id;
}
This Is Route
Route::post('/getbuffaloidformonitor/{id}','App\Http\Controllers\BuffalomonitorController#getbuffaloidformonitor')->name('getbuffaloidformonitor');
Your post route has {id} but it's not necessary. This is what you need Route::post('/getbuffaloidformonitor','App\Http\Controllers\BuffalomonitorController#getbuffaloidformonitor')->name('getbuffaloidformonitor');
pass id to the link http://127.0.0.1:8000/getbuffaloidformonitor
as you write the route
Route::post('/getbuffaloidformonitor/{id}','App\Http\Controllers\BuffalomonitorController#getbuffaloidformonitor')->name('getbuffaloidformonitor');
You are just pass id by routes Params, so the URL must like this
http://127.0.0.1:8000/getbuffaloidformonitor/yourbuffaloid
You need to change URL.
$.ajax({
method : "POST",
url: "/getbuffaloidformonitor/" + buffaloid,
data: {
'_token': $('input[name=_token]').val(),
//'id': buffaloid, remove this line
},
success : function(response) {
alert(response);
}
});
If you use this script in you blade template just use
const url = '{{ route("getbuffaloidformonitor",":id") }}'
$.ajax({
method : "POST",
url: url.replace(':id',buffaloid),
data: {
'_token': $('input[name=_token]').val(),
//'id': buffaloid, remove this line
},
success : function(response) {
alert(response);
}
});
If your routes {id} is optional just
Route::post('/getbuffaloidformonitor/{id?}','App\Http\Controllers\BuffalomonitorController#getbuffaloidformonitor')->name('getbuffaloidformonitor');
with question on your id route you can use both by pass id by route params or you can pass id by data post.
In controller
public function getbuffaloidformonitor(Request $req, $id = null)
{
// id is get from route params
$getId = $req->get('id') // this one get from data post.
}

Using AJAX with MVC 5 and Umbraco

I need to use ajax in a partial view to call a function in a mvc controller to return a calculation.
FYI, I am using MVC 5 and Umbraco 7.
I currently have the ajax code within the partial view (will want to move this to a js file at some point).
Here is the ajax code:
function GetTime(name) {
var result = "";
$.ajax({
url: '/TimeDifference/GetTimeDifference',
//url: '#Url.Action("GetTimeDifference", "TimeDifference")',
type: 'GET',
//data: JSON.stringify({ location: name }),
data: ({ location: name }),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
cache: false,
success: function (msg) {
result = msg;
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
}
});
return result;
}
Here is the Controller:
public class TimeDifferenceController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpGet]
public JsonResult GetTimeDifference(string location)
{
DateTime utc = DateTime.UtcNow;
string timeZoneName = GetTimeZoneName(location);
TimeZoneInfo gmt = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");
TimeZoneInfo local = TimeZoneInfo.FindSystemTimeZoneById(timeZoneName);
TimeSpan utcOffset = gmt.GetUtcOffset(utc);
TimeSpan localOffset = local.GetUtcOffset(utc);
TimeSpan difference = localOffset - utcOffset;
return Json(Convert.ToInt16(difference.TotalMinutes),JsonRequestBehavior.AllowGet);
}
}
The above code gives me a 404 Not Found Error:
Request URL:http://localhost:100/TimeDifference/GetTimeDifference?location=BVI&_=1511949514552
Request Method:GET
Status Code:404 Not Found
Remote Address:[::1]:100
If I use:
url: '#Url.Action("GetTimeDifference", "TimeDifference")'
The #Url.Action("GetTimeDifference", "TimeDifference") is Null so it doesn't go anywhere.
I have also tried:
#Html.Hidden("URLName", Url.Action("GetTimeDifference", "TimeDifference"))
...
url: $("#URLName").val()
Url is still Null.
I have added entries in to the Global.asax.cs for routing i.e.
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "TimeDifference", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
This doesn't seem to do anything.
I have gone through a lot of the questions raised previously and amended as per suggestions but nothing seems to work.
As I am new to this I'm sure it something very simple I am missing.
Many thanks,
HH
Your controller won't be wired automatically, and I don't think the global.asax.cs file will work either. You can either register a custom route for your controller in an Umbraco Startup Handler: https://our.umbraco.org/documentation/reference/routing/custom-routes or you can create your controller as an Umbraco WebApi Controller, which is designed for stuff like this: https://our.umbraco.org/documentation/Reference/Routing/WebApi/.
Umbraco WebAPI controllers get wired in automatically and will return either JSON or XML automatically depending on what the calling client asks for.

Parameters not populating with Ajax Call

This is my controller
[HttpPost]
public bool Sync(int? id, string name)
{
throw new NotImplementedException();
}
Here is my ajax request call that I am trying to make to this controller:
<script type="text/javascript">
var buttonClicked = document.getElementById("syncLegacy");
buttonClicked.addEventListener('click', function () { syncLegacyMake(); }, false);
function syncLegacyMake() {
$.ajax({
url: '/Legacy/Sync',
type: 'POST',
data: JSON.stringify({
id: $("#Id").val(),
name: $("#Name").val()
}),
contentType: 'application/json; charset=utf-8',
success: function (data) {
},
error: function () {
alert("error");
}
});
}
The controller gets hit however there are no values to the parameters. The values are both null.
When I look at the call itself on chrome console, the values are populated as these under Request Payload in the headers:
{id: "01", name: "Titan"}
id
:
"01"
name
:
"Titan"
Could anyone point out what I am doing wrong here? I have been able to do the same in .net 4.6.1 framework so not sure if framework changed has caused this?
have you tried the following things:
Using a Dto instead of separate simple types:
public class SyncDto
{
public int? Id {get;set;}
public string Name {get;set;}
}
// Controller action:
[HttpPost]
public bool Sync(SyncDto input)
{
throw new NotImplementedException();
}
Make Jquery stringify itself
Let jquery figure your ajax call out itself:
$.ajax({
url: '/Legacy/Sync',
type: 'POST',
data: {
id: $("#Id").val(),
name: $("#Name").val()
}
});

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

How to attach success handler to ajax proxy of Treestore in EXTJS 4?

Below is my ajax call to the server which loads the store:
function setUpStore(Id){
store = Ext.create('Ext.data.TreeStore', {
storeId:'jsonStore',
proxy: {
type: 'ajax',
url: 'fetchData.action?ID='+Id,
reader: {
type: 'json'
},
success : function(resp){
alert("success!!!");
}
}
});
}
which calls the below java method which returns a JSON object:
public String fetchJSONObj(){
HttpServletResponse res = ServletActionContext.getResponse();
HttpServletRequest req = ServletActionContext.getRequest();
ID = (String) req.getParameter("ID");
res.setHeader("Content-Type", "application/json");
VendorVO root= ServiceHelper.getInstance().getService().getData(ID);
Data = new ExtJsTreeWrapper();
Data.setText(ID);
Data.setId(ID);
Data.getChildren().add(convertVOToExtJSWrapper(root));
return SUCCESS;
}
After I get the response from the server, I do not get the alert mentioned in the success handler. Am I declaring it correctly?
Thanks
proxy hasn't got a config option called success.
Given your code you can hook on the store's load event:
function setUpStore(Id){
store = Ext.create('Ext.data.TreeStore', {
storeId:'jsonStore',
proxy: {
type: 'ajax',
url: 'fetchData.action?ID='+Id,
reader: {
type: 'json'
},
},
listeners: {
load: {
fn: function() {
// Do something here.
},
},
scope: this
}
}
});
If you do manual load, you can also pass a callback as a parameter to the load function.

Resources