VaryByParam not working with parameter, only * - ajax

I've taken a look at the other VaryByParam questions, but I haven't been able to find the answer to my question. I have an MVC site that has the following action defined:
[OutputCache(Duration = 30, VaryByParam = "TargetID")]
public JsonResult IsThingAllowed(int TargetID)
{
bool isAllowed = IsAllowed(TargetID);
return Json(isAllowed, JsonRequestBehavior.AllowGet);
}
No matter what comes in for TargetID, the cached value gets returned. However, if I change TargetID to be *, it works as expected (cached values vary by TargetID):
[OutputCache(Duration = 30, VaryByParam = "*")]
Here's the AJAX call:
$.ajax({
url: "/MyController/IsThingAllowed",
type: "POST",
data: JSON.stringify({ "TargetID": id }), // This is definitely varying!
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data, textStatus, xhr) {
updateThing(data);
},
error: function (xhr, textStatus, error) {
}
});
What am I doing wrong when the parameter is explicitly named?
EDIT: Works if we use GET instead of POST.. but POST obviously works, since it works when we use *.
Here's it working with GET:
$.ajax({
url: "/MyController/IsThingAllowed",
type: "GET",
data: { TargetID: id },
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data, textStatus, xhr) {
updateThing(data);
},
error: function (xhr, textStatus, error) {
}
});

Related

.NET 6 (Core) MVC application - problem with ajax call

.NET 6 (Core) MVC application. In view I have:
$("#mybtn").click(function () {
$.ajax({
type: "POST",
url: "/MyController/GetCustomer",
data: JSON.stringify({ 'id': 5 }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response, textStatus, xhr) {
alert(response);
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus);
}
});
});
and in controller:
[HttpPost]
public JsonResult GetCustomer(int? id) {
if (id == null) {
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json(new { msg = "Error in the request." });
}
var customer = _db.Customers.Find(id);
return Json(customer);
}
It gets to the action method in controller, but the id is always null...
What am I doing wrong?
It gets to the action method in controller, but the id is always
null... What am I doing wrong?
To begin with, you don't need to use JSON.stringify({ 'id': 5 }) as { 'id': 5 } already in json format. In addition, contentType: "application/json; charset=utf-8", is uncessary as well, Instead, you can do as following:
Correct Format:
$("#mybtn").click(function () {
$.ajax({
url: "/MyController/GetCustomer",
type: "POST",
data: { 'id': 5 },
dataType: "json",
success: function (response, textStatus, xhr) {
alert(response);
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus);
}
});
});
Note: You are getting null in your controller because of using contentType: "application/json; charset=utf-8", and additional, Json parsing here JSON.stringify() these are only valid when you are sending parameter as object fashion. Just get rid of those two part, you are done.
Output:

ajax POST int parameter in asp.net core

I am migrating my MVC project to Core and I have been having a hard time fixing all the old ajax calls.
I can pass a model and string parameters into the controller, however, ints are not working for me.
I can wrap them into a JSON object as a string parameter such as [FromBody]string objId in the controller, but then I have to parse the int val from the Json {'objId' : 1}.
Is there a way I can avoid this and just pass an int?
below is the code I am trying.
[HttpPost]
public JsonResult PassIntFromView([FromBody]int objId)
{
//DO stuff with int here
}
here is the js.
var data = { "objId": 1};
$.ajax({
url: '#Url.Action("PassIntFromView", "ControllerName")',
data: JSON.stringify(data),
type: "POST",
dataType: 'JSON',
contentType: "application/json",
success: function(data) {
//do stuff with json result
},
error: function(passParams) {
console.log("Error is " + passParams);
}
});
The objId is always 0 in the controller.
I have tried this without doing JSON.stringify(data) as well with no result.
I have also tried all the different form attribute variations.
Try to use contentType as 'application/x-www-form-urlencoded':
var data = { objId: 1 };
$.ajax({
url: '#Url.Action("PassIntFromView", "ControllerName")',
type: "post",
contentType: 'application/x-www-form-urlencoded',
data: data,
success: function (result) {
console.log(result);
}
});
Then remove the [FromBody] attribute in the controller
[HttpPost]
public JsonResult PassIntFromView(int objId)
{
//Do stuff with int here
}
I believe your issue could be that you are passing an object to the api, but trying to turn it into a primitive. I know there is already a chosen answer, but give this a whirl.
var data = { };
data["objId"] = 1; //I just wanted to show you how you can add values to a json object
$.ajax({
url: '#Url.Action("PassIntFromView", "ControllerName")',
data: JSON.stringify(data),
type: "POST",
dataType: 'JSON',
contentType: "application/json",
success: function(data) {
//do stuff with json result
},
error: function(passParams) {
console.log("Error is " + passParams);
}
});
You create a model class
public class MyModel {
public int ObjId {get;set;}
}
Your controller should expect one of these
[HttpPost]
public JsonResult PassIntFromView([FromBody] MyModel data)
{
//DO stuff with int here
}
JSON has a preference for strings not integers. You are better off to use JSON.stringify(data) to parse to your controller, convert that to a integer in the controller, then parse the string that was returned as:
var data = { objId: 1};
$.ajax({
url: '#Url.Action("PassIntFromView", "ControllerName")',//asp.net - url: 'api/controllerName/controllerFunction'
data: JSON.stringify(data),
type: "POST",
dataType: 'JSON',
contentType: "application/json",
success: function(data) {
var result = JSON.parse(data);
//do stuff with json result
},
error: function(passParams) {
console.log("Error is " + passParams);
}
});
Try this:
var data = { "objId": 1};
$.ajax({
url: '#Url.Action("PassIntFromView", "ControllerName")',
data: data,
type: "POST",
dataType: 'JSON',
contentType: "application/json",
success: function(data) {
//do stuff with json result
},
error: function(passParams) {
console.log("Error is " + passParams);
}
});
Your controller:
[HttpPost]
public JsonResult PassIntFromView(int objId)
{
//DO stuff with int here
}
Js
var data = { "objId": 1};
$.ajax({
url: "ControllerName/PassIntFromView",
data: data,
type: "POST",
dataType: 'JSON',
success: function(data.result!=null) {
console.log(data.result);
},
error: function(passParams) {
console.log("Error is " + passParams);
}
});
I got it working like this
let numberFour = JSON.stringify(4);
$.ajax({
.......
.......
data: numberFour,
type: "POST",
dataType: 'JSON',
contentType: "application/json",
......
........
});

ASP.NET MVC AJAX POST ValidateAntiForgeryToken

With my code i get a internal Server error:
#using (Html.BeginForm("", "Manage", FormMethod.Post, new { role = "form"}))
{
#Html.AntiForgeryToken()
}
<script>
function Like(id) {
var requestData = {
profileId: id,
__RequestVerificationToken: $('[name=__RequestVerificationToken]').val(),
};
$.ajax({
url: '/Manage/Like',
type: 'POST',
data: JSON.stringify(requestData),
dataType: "json",
contentType: 'application/json; charset=utf-8',
error: function (xhr) { alert('Error: ' + xhr.statusText); },
success: function (result) {},
async: true,
processData: false
});
}
</script>
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Like(string profileId)
{ ... }
If i remove [ValidateAntiForgeryToken] everything works fine, but i lose the sercurity. How can i fix the internal server error?
I see in fiddler SyntaxView 2 requests:
/Manage/Like
{"profileId":13,"__RequestVerificationToken":"jH2ofYlcTiHl8lixW_ANEHOg5KgwRh5Xl43lQfGkDFh55jX-x5cmz4RfPtbDfu92oQsTM7zsop83ldfbxMdIIELYZ0kfByFcXjUp-5mwyKZcQzjXP2gy6qW0iQOtLsqaDjFSzoxnyqM2MD42CbItzw2"}
/Manage
__RequestVerificationToken=MNiKOJHZg7BGaTNccOjrR2Obf_nPhKfcwIPZVBUl53G368n5euzB4y1htH47VKg3V3mHfxkjYZDz6iPepQ7jpeXGARtlj6vV74B8zQbp4by9JR4Rcz4sHANm3WHb6WAXaLcsnFvWJth_8c98XKda5w2
Taking this from a sim. question here include antiforgerytoken in ajax post ASP.NET MVC
function Like(id) {
var form = $('form');
var token = $('input[name="__RequestVerificationToken"]', form).val();
$.ajax({
url: '/Manage/Like',
type: 'POST',
data: { __RequestVerificationToken: token, profileID: id },
error: function (xhr) { alert('Error: ' + xhr.statusText); },
success: function (result) {},
async: true,
processData: false
});
}

Ajax Post in mvc returns error all the time

I fairly new to Ajax post, and I wonder if someone could help me with why i keep getting the error message.
VideoController
[HttpPost]
public ActionResult Check(string userid, string streamid)
{
return Json(new { success = true });
}
The reason why the httppost is fairly empty yet is just to test if it works before i start writing the code.
Jquery
var userID = '#User.Identity.GetUserId()';
var defaultContext = window.location.hash === "" ? XSockets.Utils.guid() : window.location.hash.substr(1);
//alert(defaultContext);
$.ajax({
url: '/video/check',
type: 'POST',
dataType: 'json',
data: JSON.stringify({
userid: userID,
streamid: defaultContext
}),
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data.success);
},
error: function (error) {
alert(error.status);
}
});
I keep getting throw into my error: function and if I debug I never hit the [httpPost] Method
Can someone help
Update
I get a 404 in the alert.
RouteConfig
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
Try not to hardcore the URL:
var tURL = '#Url.Action("Check", "Video")';
$.ajax({
url: tURL ,
type: 'POST',
dataType: 'json',
data: JSON.stringify({
userid: userID,
streamid: defaultContext
}),
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data.success);
},
error: function () {
alert("error");
}
});
Server:
[HttpPost]
public JsonResult Foo(string userid, string streamid)
{
return new JsonResult{ Data = new {success = true}};
}
Client:
$.post('/home/foo',{userid:'123', streamid:'bar'}, function(r) {
console.log(r);
});
EDIT - If you prefer the $.ajax way instead of $.post:
$.ajax({
url: '/home/foo',
type: 'POST',
dataType: 'json',
data: JSON.stringify({
userid: '123',
streamid: 'bar'
}),
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data.success);
},
error: function () {
alert("error");
}
});
The confusing thing is that you mix XSockets.NET with AJAX... When you have XSockets in there, why pass anything over HTTP with AJAX? You can just as easy pass it to XSockets and call your service layer from there. Just a friendly pointer.

ComponentOne excel and asp.net MVC

I am working on a action that returns excel file - the excel is created using ComponentOne dll.
Here is what I have so far
public ActionResult DownloadExcel()
{
C1XLBook testBook = new C1XLBook();
XLSheet s1 = testBook.Sheets[0];
MemoryStream ms = new MemoryStream();
testBook.Save(ms,FileFormat.Biff8);
return File(ms, "application/ms-excel");
}
But I am getting a invalid Json error
On the JS side I have the following code
$.ajax({
contentType: 'application/json, charset=utf-8',
type: "POST",
url: /test/DownloadExcel,
cache: false,
dataType: "json",
success: function (response) {
alert("good");
},
error: function (xhr, ajaxOptions, thrownError) {
alert("error");
}
});
What am I doing wrong?

Resources