HttpResponseMessage Headers.Location Seemingly Being Ignored - http

I have the following Web Api method, which works fine as far as creating a new product and setting the location. I know this because I check the response header in Google developer tools and see that it is valid. If I cut and paste the location from tools to the browser, the page loads fine. However, it will not load as a result of returing the response from the method.
public HttpResponseMessage PostProduct(Product product)
{
productsRepository.Create(product);
var response = Request.CreateResponse<Product>(HttpStatusCode.Created, product);
string uri = Url.Link("ProductsIndex", null);
response.Headers.Location = new Uri(Request.RequestUri,"/Products/testview");
return response;
}
The jQuery that calls PostProduct:
$("#createjQButton").click(function () {
var product = { Name: $("#Name").val(), Category: $("#Category").val(), Price: $("#Price").val() };
var json = JSON.stringify(product);
// Send an AJAX request to create a new product
$("#createjQButton").click(function () {
var product = { Name: $("#Name").val(), Category: $("#Category").val(), Price: $("#Price").val() };
var json = JSON.stringify(product);
$.ajax({
url: '/api/productsapi',
cache: false,
type: 'POST',
data: json,
contentType: 'application/json; charset=utf-8'
});
return false;
});
Why is the location being ignored?

Well, I added
statusCode: {
201 : function() {
window.location.replace("/Products/testview");
}
to my jQuery click function and got to the desired page that way. But should not the original way have worked?

Related

Ajax data not passing to controller

I have a problem where the data in the ajax isn't passing the sessionStorage item. I have tried using JSON.stringify and added contentType: 'application/json' but still it's not passing. Can this be done using POST method? Also, I have debugged and returned those sessionStorages, hence the problem isn't because the sessionStorge doesn't contain data.
Here my function:
function functionA() {
$.ajax({
url: URLToApi,
method: 'POST',
headers: {
sessionStorage.getItem('token')
},
data: {
access_token: sessionStorage.getItem('pageToken'),
message: $('#comment').val(),
id: sessionStorage.getItem('pageId')
},
success: function () {
$('#success').text('It has been added!"');
},
});
}
Check below things in Controller's action that
there should be a matching action in controller
name of parameter should be same as you are passing in data in ajax
Method type should be same the ajax POST of the action in controller.
function AddPayment(id, amount) {
var type = $("#paymenttype").val();
var note = $("#note").val();
var payingamount = $("#amount").val();
$('#addPayment').preloader();
$.ajax({
type: "POST",
url: "/Fixed/AddPayment",
data: {
id: id,
amount: payingamount,
type: type,
note: note
},
success: function (data) {
}
});
}
Here is the working code from my side.
Check with this, and for the header part you need to get it from the Request in action
The solution to this problem has been found. The issue was the sessionStorage, hence I've passed it directly to the URL and now it working as follows:
function functionA() {
$.ajax({
url: 'http://localhost:#####/api?id=' + sessionStorage.getItem('pageId') + '&access_token=' + sessionStorage.getItem('pageToken') + '&message=' + $('#comment').val(),
method: 'POST',
headers: {
sessionStorage.getItem('token')
},
success: function () {
$('#success').text('It has been added!"');
},
});
}

How can I call controller post action from jquery (in custom view page) in mvc .net web app

I am creating a web application for event management using .net mvc and jquery.
I created a mvc web app.contoller named SeatPlansController and model named SeatPlanes and I am able to insert the data to database.
But I am not able pass the data from jquery to database using the mvc controller.
My controller action code is as shown below
// GET: SeatPlans/Create
public ActionResult Create()
{
return View();
}
// POST: SeatPlans/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(String seat_id, String seat_no)
{
int id = 10;
SeatPlans S = new SeatPlans();
S.seat_id = seat_id;
S.seat_no = seat_no;
if (ModelState.IsValid)
{
db.SEATPLAN.Add(S);
db.SaveChanges();
// return RedirectToAction("Index");
}
return View(S);
}
In post create controller Id is primary key, so I want to pass seat_id,seat_no as argument and it should update the database.
I used following javascript
function getPerson(id) {
$.ajax({
type: "GET",
url: '#Url.Action("create", "SeatPlanesController")',
contentType: "application/json; charset=utf-8",
data: {eat_id :6, seat_no:8},
dataType: "json",
success: function (result) {
alert(result);
//window.locationre = result.url;
}
});
}
I am able to run the create get method using
http://localhost:52348/SeatPlans/Create
but how can I run post method directly from browser with argument
something like
http://localhost:52348/SeatPlans/Create/2/3t/e
I have changed the script as bellow,it works for GET method but if i made TYPE:"post" it popup an alert box with alert
"localhost:52348 says:
internal server error"
$(document).ready(function () {
$("button").click(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '#Url.Action("Create", "SeatPlans", new { Area = "" })',
data: { seat_id: "34", seat_no: "98" },
dataType: "json",
async: false,
success: function (result) {
$("#div1").html(result);
},
error: function (abc) {
alert(abc.statusText);
},
});
});
});
Finally i got the sollution
i changed the script as bellow
//jQuery.noConflict();
// var $j = jQuery.noConflict();
function clickevent()
{
var form = $("#frm");
var token = $('input[name="__RequestVerificationToken"]', form).val();
$.ajax({
type: "post",
// headers: { "__RequestVerificationToken": token },
url: '#Url.Action("Create", "SeatPlans")',
data: {
seat_id: "34", seat_no: "98"
},
success: function (result) {
$("#div1").html(result);
}
});
}
and change the create post method as bellow
<pre>
public ActionResult Create(String seat_id, String seat_no)
{
int id = 10;
SeatPlans S = new SeatPlans();
S.seat_id = seat_id;
S.seat_no = seat_no;
if (ModelState.IsValid)
{
db.SEATPLAN.Add(S);
db.SaveChanges();
// return RedirectToAction("Index");
}
return View(S);
}

MVC 5 JsonResult returns html?

I have been following this tutorial https://www.youtube.com/watch?v=c_MELPfxJug regarding ajax and JsonResult in HomeController
I did the tutorial, however for some reason the controller is returning Html and not json
I did not change one line of code, but it's failing with parseError on the javascript side.
when i look at the response i see an html page, not a json object.
Controller code:
public JsonResult DoubleValue(int? Value)
{
if (!Request.IsAjaxRequest() || !Value.HasValue)
{ return null; }
else
{
int DoubleValue = Value.Value * 2;
var ret = new JsonResult
{
Data =
new { DoubleValue = DoubleValue }
};
return ret;
}
}
cshtml:
#using (Html.BeginForm())
{
#Html.TextBox("txtAmount",0)
<button id="btnDoubleValue">DoubleIT</button>
<div id="lblMessage"></div>
}
#section Scripts{
<script type="text/javascript">
$(function () {
$('#btnDoubleValue').on('click', function() {
$.ajax({
type: 'POST',
url: '#Html.Action("DoubleValue")',
data: { 'Value': $('#txtAmount').val() },
datatype: 'json',
cache: 'false'
}).success(function (data) {
var t = data;
$('#txtAmount').val(data.DoubleValue);
}).error(function (x, o, e) {
$('#lblMessage').html('error was found: ' );
});
return false;
})
});
</script>
}
found the error
I was using Html.Action and not Url.Action -> just human error I suppose
from the reference:
Html.Action - returns the result as an HTML string.
It works now
$.ajax({
type: 'POST',
url: '#Url.Action("DoubleValue")', //<--- Url.Action
data: { 'Value': $('#txtAmount').val() },
datatype: 'json',
cache: 'false'
I guess this must be the default error page, you are probably getting a 500 response and you must use the Network tab of your browser to see the real problem.
In your browser open developer tools using F12 key and navigate to Network tab.
Make the appropriate actions to do the ajax request (click on that button)
Click on the request row
Navigate to Response tab.
From there you can watch the real request your ajax does and the response from the server.

Backbone Collection Fetch() doesnt work

I have a jquery mobile based implementation of a mobile website and now learning backbone.js and rethinking the app to better organize it.
var membership = Backbone.Model.extend();
var memberships = Backbone.Collection.extend({
model: membership,
parse: function (resp, xhr) {
},
url: "/groups.svc/memberships/azxcv01"
});
var col1 = new memberships();
col1.fetch({ success: function () {
console.log(col1);
}
});
In chrome, I see that the URL is formatted well and returns valid JSON back. The parse() event also gets a valid resp. But the console.log() above displays and empty array "[ ]".
What am I missing ?
try this,
here link to fiddle http://jsfiddle.net/w7xeb/ (updated)
var membership = Backbone.Model.extend();
var memberships = Backbone.Collection.extend({
model: membership,
parse: function (resp, xhr) {
return resp;
},
});
var col1 = new memberships();
col1.fetch({
url : "/restful/fortune",
success: function () {
console.log(col1);
}
});
​
response
$.mockjax({
url: "/restful/fortune",
responseTime: 750,
contentType: "text/json",
responseText: [{
a:'a'
},{
a:'b'
},{
a:'c'
}]
});

Message from webpage undefined

I am returning a simple string from a webmethod to a Javascript function.
I am using an AJAX enabled website in ASP.NET 2.0. I get the date in firefox but inside IE 8 it returns undefined.
Do I have to parse the string in the JSON format using some serialize class? In my webmethod, I am just using:
return DateTime.Now.ToString();
$(document).ready(function(){
var pageUrl = '<%=ResolveUrl("~/test/test.aspx")%>';
// Test
$('#<%=trgNo.ClientID%>').change(function(){
var trgId = $(this+'input:checked').val();
$.ajax({
type: "POST",
url : pageUrl+ '/getDet',
data : '{categ: "' +trgId + '"}',
contentType:"application/json; charset=utf-8",
dataType:"json",
success:OnSuccess,
failure: function(msg){
if(msg.hasOwnProperty("d"))
alert(msg.d);
else
alert('error fetching values from database');
}
});
});
function OnSuccess(msg)
{
if(msg.hasOwnProperty("d"))
alert(msg.d);
else
alert(msg);
}
});
Edit
It seems the success function is firing the problem is with response 'alert(msg)' works in firefox but not in IE 8 with asp.net 2.0
Maybe you dont want to use this, but I´m very happy with the asp net ajax build in function, since it builds a header, that works properly on browsers.
$(document).ready(function(){
var pageUrl = '<%=ResolveUrl("~/test/test.aspx")%>';
// Test
$('#<%=trgNo.ClientID%>').change(function(){
var trgId = $(this+'input:checked').val();
var proxy = Sys.Net.WebServiceProxy;
proxy.invoke("", // if current page "", if webservice "/srv.asmx"
"getDet", //method name
false, //post = true, get = false
{ categ : trgId }, //javascript object
OnSuccess, // Success Function
onError, // Error Function
{ yourOwn : userData } // Custom User Data to Handler
);
});
function OnSuccess(response, usercontext)
{
// usercontext.yourOwn === userData;
// response is sent WITHOUT "d", it is removed internally by the proxy
alert(response);
}
});
Dont forget to include the ScriptManager...

Resources