jQuery API call to Entity Framework API Put method - javascript

I am using jquery to make an API call to an Entity Framework API Controller and I am trying to call the Put Method:
[ResponseType(typeof(void))]
public IHttpActionResult PutProfileIDClass(int id, ProfileIDClass profileIDClass)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != profileIDClass.id)
{
return BadRequest();
}
db.Entry(profileIDClass).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!ProfileIDClassExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
But when I make the API call via jQuery I get this error: 405 (Method Not Allowed)
What Am I doing wrong?
Here is my API call
var data = {
id: result.data[0].id,
profileID: result.data[0].profileID,
taken: 'true'
};
var json = JSON.stringify(data);
$.ajax({
url: '/api/ProfileIDAPI?id=' + result.data[0].id,
type: 'PUT',
contentType: "application/json; charset=utf-8",
data: json,
success: function (results) {
}
});

If you want to do a PUT request you should use the method: 'PUT' as part of your $.ajax call:
$.ajax({
url: '/api/ProfileIDAPI?id=' + result.data[0].id,
method: 'PUT',
contentType: "application/json; charset=utf-8",
data: json,
success: function (results) {
}
});

Do you have it installed on IIS? In that case, you have to configure it to handle your "PUT" request.
Right click on your website in the sidebar and go to properties.
Go to the "Home Directory" Tab
In the "applications settings", click on the "configuration" button
In the "Applications configuration" Window, there should be a Mappings Tab
Simply choose which file extensions you want to have mapped (in my case i wanted ASP to map GET, PUT, POST & DELETE), comma delimited. And thats it, not even a restart required.
Hope this helps

Related

Redicrect in Spring MVC

I have a method GET in js
$(".btn-sm").click(function() {
$.ajax({
url: '/check_rating/'+this.value,
type: 'GET',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
success: function (response) {
alert(response.status);
},
error: function () {
alert("error");
}
});
});
url is such like this /check_rating/1. Controller
#RequestMapping(value = "/check_rating/{id}",method = RequestMethod.GET)
public String check_rating(#PathVariable("id")Long id, RedirectAttributes redirectAttributes){
List<Rating>rating = ratingService.findAllRatingsByIdStudentAndStageOfApproveGreaterThan(id,0);
redirectAttributes.addFlashAttribute("rating",rating);
return "redirect:/students_rating";
}
#RequestMapping(value = "/students_rating",method = RequestMethod.GET)
public String student_rating(#ModelAttribute("rating") List<Rating>rating, ModelMap model){
model.addAttribute("rating",rating);
return "students_rating";
}
}
I need redirect to /students_rating, but after sending get method by url /check_rating/1 i still remain on the same page and redirect is now working, but on console i have log such this
MODEL = {rating=[student_rating.entity.Rating#7856e7f, student_rating.entity.Rating#6a369ebf, student_rating.entity.Rating#7ed68627], org.springframework.validation.BindingResult.rating=org.springframework.validation.BeanPropertyBindingResult: 0 errors}
o.s.web.servlet.DispatcherServlet - Rendering view [org.springframework.web.servlet.view.JstlView: name 'students_rating'; URL [/pages/students_rating.jsp]] in DispatcherServlet with name 'dispatcher'
DEBUG o.s.web.servlet.view.JstlView - Added model object 'rating' of type [java.util.ArrayList] to request in view with name 'students_rating'
o.s.web.servlet.view.JstlView - Added model object 'org.springframework.validation.BindingResult.rating' of type [org.springframework.validation.BeanPropertyBindingResult] to request in view with name 'students_rating'
o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'requestDataValueProcessor'
o.s.web.servlet.view.JstlView - Forwarding to resource [/pages/students_rating.jsp] in InternalResourceView 'students_rating'
o.s.web.servlet.DispatcherServlet - Successfully completed request
o.s.s.w.a.ExceptionTranslationFilter - Chain processed normally
o.s.s.w.c.SecurityContextPersistenceFilter - SecurityContextHolder now cleared, as request processing completed
students_rating.jsp
<tbody id="tBody">
<c:forEach items="${requestScope.rating}" var="rating">
<tr><td class="column"><c:out value="${rating.id}"></c:out></td><td><c:out value="${rating.date}"></c:out></td><td><c:out value="${rating.score}"></c:out></td></tr>
</c:forEach>
</tbody>
You can not redirect page with Location header for ajax requests. You must get some response text for ajax and redirect user using parsed response text. This is how to redirect browser with JS code
if (responseText == 'OK') {
document.location.href = 'http://example.com/';
}
If you are hitting controller using AJAX request then Your Spring mvc controller should return some response and based on the response you can redirect the request in your view page.
Update ajax call to below code :
$(".btn-sm").click(function() {
$.ajax({
url: '/check_rating/'+this.value,
type: 'GET',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
success: function (response) {
if (responseText == 'OK') {
window.location.href = '<--replace this with controller URL-->';
}
},
error: function () {
alert("error");
}
});
});
You could use document.location.href but it is deprecated in html5.

Ajax POST int to MVC

I'm trying to POST an INT with Ajax to my MVC controller.
The script debugging confirms that my variable is an INT with a value (for example 8 and not a string "8"). All lines of code are executed and
I recive my Alert error message.
I've got a breakpoint inside of my Action in the controller but I never get that far. I get a notice in my Action that a request failed, but it only say
"POST Order/Delete". My Controller name is OrderController and Action name is Delete.
My JavaScript:
//Delete order
$(".deleteOrder").on("click", function () {
var id = parseInt($(this).attr("id"));
if (id !== null) {
$.ajax({
url: "/Order/Delete",
method: "POST",
contentType: "application/JSON;odata=verbose",
data: id ,
success: function (result) {
alert("Ok")
},
error: function (error) {
alert("Fail");
}
});
}
});
My MVC Action
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(int id)
{
List<OrderRow> lstOrderRow = new List<OrderRow>();
lstOrderRow = db.OrderRows.Where(x => x.OrderId == id).ToList();
foreach(var row in lstOrderRow)
{
db.OrderRows.Remove(row);
}
Order order = new Order();
order = db.Orders.Find(id);
db.Orders.Remove(order);
db.SaveChanges();
return RedirectToAction("index");
}
You should either use the url like this by removing data field
url: "/Order/Delete/" + id,
or send the id in data as below
data: {id: id},
This works for me:data: JSON.stringify({ id: id})
dataType: "json",
contentType: 'application/json; charset=utf-8',

The requested resource does not support http method 'DELETE'

I have a web service created by Asp API, and i am trying to consume it by javascript ajax caller .. it works fine with GET & POST .. but when i tried to call DELETE function it returns message [The requested resource does not support http method 'DELETE'.]
and this is my code
Server code (API C#)
[HttpDelete]
public bool Delete(int id)
{
try
{
var model = db.PostsLikes.First(f => f.PostLikeID == id);
db.PostsLikes.Remove(model);
db.SaveChanges();
return true;
}
catch (Exception)
{
return false;
}
}
Client code (Javascript)
function (postLikeid) {
var result = $.ajax({
url: "/api/PostsLikes/",
type: "DELETE",
async: false,
data: postLikeid ,
contentType:"application/json"
}).responseText;
return result;
}
Problem is your IIS configuration is not accepting DELETE verbs. In the Handler Mappings section of IIS you can add the Delete verb.
Add it in delete method.
[HttpDelete]
[Route("api/PostsLikes/{id}")]
function DeleteFruitRecord(FruitID) {
var del = confirm("Are you sure you want to delete this recored?");
if (del) {
$.ajax({
type: "DELETE",
url: "api/FruitRec/DeleteFruit" + FruitID,
contentType: "json",
dataType: "json",
success: function (data) {
alert("Successsfully deleted…. " + FruitID);
GelAllEmployees();
},
error: function (error) {
alert(error.responseText);
}
});
}

ajax post call not working

I am trying to call MVC Controller from jquery but not able to place the call. Is there any problem in below code
Please figure out that if any problem and also I am not getting any error.
url="http://localhost:49917/Account/SaveAddress"
this.SaveAddress = function (url, addressData)
{
$.ajax({
type: "POST",
url: url,
dataType: "json",
data: JSON.stringify(addressData),
contentType: 'application/json; charset=utf-8',
success: function (responseDetail) {
},
error:function(e)
{
},
});
return 0;
};
public async Task<ActionResult> SaveAddress(AddressListViewModel addressListVM)
{
bool response;
string message;
if (addressListVM.ID <= 0)
{
response = await Task.Run(() => AccountManager.Instance().AddAddress(addressListVM));
message = response ? "New address added successfully." : "Failed to add new address.";
}
else
{
response = await Task.Run(() => AccountManager.Instance().UpdateAddress(addressListVM));
message = response ? "Selected address updated successfully." : "Failed to update selected address.";
}
ModelState.Clear();
return Json(new { responsestatus = response, message = message }, JsonRequestBehavior.AllowGet);
//return PartialView("_AddressDetail", BuildAddressListEntity(
// UserManager.FindById(User.Identity.GetUserId()), response, message, addressListVM.ID, true));
}
Yes, you are missing a closing bracket at the end of the this.saveaddress function
this.SaveAddress = function (url, addressData)
{
$.ajax({
type: "POST",
url: url,
dataType: "json",
data: JSON.stringify(addressData),
contentType: 'application/json; charset=utf-8',
success: function (responseDetail) {
},
error:function(e)
{
},
});
after all of that .. you need one more closing bracket:
}
;)
What does the console display? If you are using Chrome then right-click, choose Inspect, and find the Console tab. If you are calling the AJAX function correctly then something must be displayed in this Console tab which will probably lead you in the right direction better than I could with the information I have.
Put a breakpoint in your success and error functions. If it hits the error function then the issue is either that the controller action was not found or that the data is not valid json (either the post data or return data). You should add the errorThrown parameter to the error function so you can easily see what the issue is. You also do not need to stringify the data if it is already valid json, but if it is a string representing json data, you will need to use json.parse (sorry for the incorrect case).

Crossdomain Ajax call to Service isn't working

I'm using ASP MVC and I'm trying to call a service that's on another one of my MVC websites.
I'm trying to use the following Ajax call.
function SomeFunction(decision) {
if (decision == false)
decision = "no";
else
decision = "yes";
var input = {
LogEventType:"PageView",
CurrentPage: "invitation/?decision=" + decision + "&id=" + 32323,
};
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "https://somewebsite.com/api/ClickStream/LogWebEvent/",
data: JSON.stringify(input),
crossDomain: true,
dataType: 'jsonp',
headers: {
'Access-Control-Allow-Origin': '*'
},
success: function (data) {
alert("We're awesome")
},
error: function () { console.log("Call to SomeFunction failed.") }
});
}
I don't get any visible errors and I also put breakpoints on the service and inside of the success/error function of the ajax call but it never reaches any of them.
Anyone see where I messed up?
EDIT:
Here is the Web Apis function I'm trying to access
[ActionName("LogWebEvent")]
[HttpPost]
public void LogWebEvent(ClickStreamEventDto data)
{
try
{
_clickstreamLogger.LogWebEvent(data);
}
catch (Exception ex)
{
}
}
Where ClickStreamEventDto is
public class ClickStreamEventDto: Analytics.IAnalyticEventDto
{
public string LogEventType { get; set; }
public string CurrentPage { get; set; }
}
When hitting cross domain sites, with either CORS or JSONP, make sure they are both HTTP or both HTTPS.
Make sure that when HTTPS is involved, that both site's certificates have been accepted. You may need to hit the HTTPS site in another window, and accept the certificate if there is no trust relationship to the issuer.

Categories

Resources