ComponentOne excel and asp.net MVC - asp.net-mvc-3

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?

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 dont call WebMethod but returns HTML

I had read a lot of questions here on Stackoverflow about AJAX calls to WebMethods, and I tried a lot of things and nothing works.
My AJAX method doesnt call the WebMethod on server side but returns success and the entire HTML of the page.
This is the AJAX:
$("[id*=butLogin]").click(function () {
var obj = {};
obj.pEmail = "EMAIL"; //$.trim($("[id*=txtName]").val());
obj.pPassword = "PASSWORD"; //$.trim($("[id*=txtAge]").val());
$.ajax({
type: "POST",
url: "login.aspx/logOn",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
},
failure: function (msg) {
alert(msg.d);
},
error: function (msg, merr, derr) {
alert(msg.d);
}
});
return false;
});
And this is the WebMethod:
[System.Web.Services.WebMethod]
public static string logOn(string pEmail, string pPassword)
{
return "logged";
}
I believe is a simples mistake.
Thanks for your help.

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.

VaryByParam not working with parameter, only *

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

Resources