Browser tries to open application/json as a file - javascript

I'm having a problem with my JSON response in my MVC 3 application. When JSON is responding, my browser cannot handle application/json and tries to open it as a file. However, I'm recieving the correct data in the file.
I've added this to my Global.asax file:
ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());
This is my javascript code:
$('#register).submit(function () {
if ($(this).valid()) {
var ai = {
Firstname: $("#Firstname").val(),
Lastname: $("#Lastname").val(),
Email: $("#Email").val()
};
var json = $.toJSON(ai);
$.ajax({
url: '/Person/Create',
type: 'POST',
dataType: 'json',
data: json,
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert("Success");
},
error: function (data) {
alert("Error");
}
})
}
});
And this is my ActionResult method:
[HttpPost]
public ActionResult Create(Person person)
{
if (ModelState.IsValid)
{
db.Personer.Add(person);
db.SaveChanges();
}
return Json(new { Success = person.ID > 0, Firstname = person.Firstname, Lastname = person.Lastname });
}
I've also added .json (application/json) to the MIME-list in IIE.

If you're trying to access a file with JSON headers in Firefox directly (meaning: you're entering the URL into the address bar), Firefox will download it as a file. However, when you call your JSON in an AJAX request, it'll work the way you want it to.

Related

Ajax POST an object with javascript, but the value in backend is null, why?

So on button click there is a function sendEmail(). Alert is working fine, I can see my datas there. But on backend I can't see anything, just everything is null.
function sendEmail() {
var datas = new Object();
datas.mail = $('#contactDropdownList').val();
datas.mailobject = $('#emailObject').val();
datas.text = $('#emailText').val();enter code here
alert(datas.mail + datas.mailobject + datas.text);
$.ajax({
type: "POST",
dataType: "json",
url: "/Email/sendEmail",
contentType: 'application/json; charset=UTF-8',
data: JSON.stringify({ items: datas }),
success: function (data) {
console.log(data);
//do something with data
},
error: function (jqXHR, textStatus, error) {
//log or alert the error
console.log(error);
}
});
}
C# code:
public class MyClass
{
public string Email { get; set; }
public string Object { get; set; }
public string Text { get; set; }
}
[HttpPost]
public IActionResult sendEmail(MyClass items)
{
return Json(new { data="Ok" });
}
items.Email, items.Object and items.Text are null.
And the return valu is null as well, because in javascript success: function (data) { console.log(data);
is empty string.
What can be the problem? Thank you!
Model binder expects json content to match C# class. Your datas object should look like that
var datas = {
email: $('#contactDropdownList').val(),
object: $('#emailObject').val(),
text: $('#emailText').val()
}
Since you wrapped your object ({ items: datas }), you may think it will be mapped to sendEmail(MyClass items), but in reality items name does not matter, you can change variable name to any other name you like
Make sure you apply [FromBody] attribute to your parameter like that
[HttpPost]
public IActionResult sendEmail([FromBody]MyClass items)
Complete demo:
<script>
function sendSmth() {
var data = {
Email: 'email',
Object: 'object',
Text: 'text'
};
$.ajax({
type: "POST",
dataType: "json",
url: "/home/index",
contentType: "application/json",
data: JSON.stringify(data),
success: function (datas) {
console.log(datas)
}
})
}
</script>
And controller
[HttpPost]
public IActionResult Index([FromBody]MyClass obj)
{
return View();
}
As someone has noted, you have a mismatch between what you're sending to the controller and what the model the modelbinder is expecting. You can also vastly simply your AJAX code:
function sendEmail() {
var data = {
Email: $('#contactDropdownList').val(),
Object: $('#emailObject').val(),
Text: $('#emailText').val()
};
$.post("/Email/sendEmail", data)
.done(function (response) {
console.log(response);
//do something with response
})
.fail(function (jqXHR, textStatus, error) {
//log or alert the error
console.log(error);
});
}
You don't really need to specify the content type or data type - the $.post helper's defaults work just fine for what you've shown.

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',

Ajax GET call to webAPI

In my javascript file i am trying to make a GET Request to my webAPI, the entire request is ignored. the two alerts before and after the request are outputted but nothing within my request.
This is my GET request made in my javascript file:
alert("before Get");
$.ajax({
url: '/api/Map/',
type: 'GET',
dataType: 'json',
success: function (data) {
alert(data);
},
error: function () {
alert("error in request");
}
});
alert("after Get");
My WebAPI file and the method im trying to get:
// GET: api/Map
public IEnumerable<string> Get()
{
SetContext();
List<ICoordinate> BoundingBox = CreateBoundingBox(_LoadedConfiguration.StartPosition);
List<string> LayerNames = _LoadedConfiguration.GetAllLayerNames();
Map LoadedMap = new Map(BoundingBox, LayerNames, _persistenceFactory, _LoadedConfiguration);
GeoJson.IGeoJsonGeometry MapFeatureCollections = (IGeoJsonGeometry)LoadedMap.GetAsGeoJsonObject();
return new string[] { MapFeatureCollections.ToString()};
}
I am trying to return the string of "MapFeatureCollections"

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);
}
});
}

MVC 4 APIController not receiving POST data

Sure this had been dealt with many times... but.. just cant see what im doing wrong!
This is a simple JS script that Posts data back to ApiController.
function WebCall(url,parameterObject, callBackFunction) {
this.callbackfunction = callBackFunction;
this.parameterObject = parameterObject;
this.url = url;
self = this;
this.GetData = function () {
//self = this;
$.ajax({
//dataType: "json",
type: "POST",
url: self.url,
data: JSON.stringify(self.parameterObject),
contentType: "application/json;charset=utf-8",
success: function (data) {
self.callbackfunction.call(this, data);
},//self.GotData,
error: function (xhRequest, ErrorText, thrownError)
{
alert("error : " + ErrorText)
},
complete: function () {},
})
}
}
The data being sent (parameterObject) is simply
var postData = {
clientId: id
}
The c# code in the controller is :
public class ClientPostObject
{
public string clientId;
}
public class ClientDetailController : ApiController
{
[HttpPost]
public ClientDetailWidgetData GetClient(ClientPostObject clientObject)
{
return new ClientModel().GetClientDetail(clientObject.clientId);
}
}
In Google chrome developer tools, the XHR is showinf 'form Data' as clientId:A0001 - so that looks ok?
No matter what I try (and I'be been through many suggestions on the web), the post data is not there.
Sure its something simple.... Thanks in advance.
Unless you're planning on using a full-on form to submit to this method at some other point, it doesn't really make sense to ask the model binder to attempt to bind to a complex type when you're just using one property. Change your method signature to:
[HttpPost]
public ClientDetailWidgetData GetClient(int clientId) // or whatever type clientId represents
{
return new ClientModel().GetClientDetail(clientId);
}
I'd also recommend adding Glimpse at some point (http://getglimpse.com/) so that you can see how the model binding and/or routing of your app works.
Try to ditch contentType and don't stringify data:
$.ajax({
type: "POST",
url: self.url,
data: self.parameterObject,
success: function (data) {...},
...
});

Categories

Resources