I'm just looking at some Ajax requests in Fiddler whilst testing some exception handling classes and code in my application and I'm not sure my requests are well formed and as they should be.
My Javascript is:
$(function () {
$('#createentry').submit(function () {
e.preventDefault();
$.ajax({
url: this.action,
type: this.method,
dataType: "json",
data: $(this).serialize(),
success: function(result) {
$('#entries-list').append("<li>" + $('#newentry').val() + "</li>");
$('#newentry').val('').blur();
},
error: function (xhr)
{
try
{
var json = $.parseJSON(xhr.responseText);
alert(json.errorMessage);
}
catch (e)
{
alert('something bad happened');
}
}
});
return false;
});
});
In Fiddler the request looks like:
Host: localhost:54275
User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64; rv:20.0) Gecko/20100101 Firefox/20.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-gb,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://localhost:54275/Diary
Cookie: __RequestVerificationToken= <snipped for brevity>
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded
Content-Length: 216
I would expect the Accept: header to be set to json automatically I guess that's an incorrect assumption on my part, how is this set?
Also if I looks at the result of this in my action method the value is always false:
[HttpPost, ValidateAntiForgeryToken, JsonExceptionFilter]
public JsonResult PostNewEntry(DiaryEntryViewModel diaryEntry)
{
var req = Request.IsAjaxRequest();
req always = false so my JsonExceptionFilter isn't kicking in and taking care of the error reporting as expected.
Is there also a defined way of forcing only accepting requests correctly setup as Ajax requests in MVC?