I'm trying to implement file download functionality thru ajax call in MVC.
After calling of controller method i always have a "parseerror", can somebody explain me why?
my ajax:
tab.on("click", ".FileDownload", function (e) {
//$('#uploadStatus').html("ok");
var tr = $(this).closest("tr");
var id = tr.data("id");
$.ajax({
type: "POST",
url: "/File/FileDownload",
//contentType: false,
//processData: false,
//dataType: "json",
data: { fileId: id },
success: function (data) {
$('#uploadStatus').html("ok");
},
error: function (err) {
alert(err.statusText);
}
});
});
and controller:
[HttpPost]
public FileResult FileDownload(int? fileId)
{
FileDBEntities db = new FileDBEntities();
tblFile file = db.tblFiles.ToList().Find(p => p.id == fileId.Value);
return File(file.Data, file.ContentType, file.Name);
}
with simple download link in razor it works, but not with ajax.
What am I doing wrong here?
Why not simple use
tab.on("click", ".FileDownload", function (e) {
//$('#uploadStatus').html("ok");
var tr = $(this).closest("tr");
var id = tr.data("id");
window.location = window.location.origin + '/File/FileDownload?fileId=' + id;
});
[HttpGet]
public FileResult FileDownload(int? fileId)
Related
I have an issue with a simple jQuery $.post in my application. I have tried many methods and solutions on the internet to no avail. When post request is sent I see 400 error
public class RecoveryAdhocInvoicingModel : PageModel
{
Public IActionResult OnPostDoJob(string invNo, string account)
{
//var emailAddress = Request.Form["emailaddress"];
// do something with emailAddress
return new JsonResult("");
}
}
In my script the $.post method is called via button click:
$('#submitBtnUpdateJob').click(function (evt) {
var formdata = new FormData();
formdata.append("invNo", $('#adhocInvoiceNumber').val());
formdata.append("account", $('#invoiceAccountInput').val());
$.post(window.location.href + '?handler=DoJob', JSON.stringify(formdata), function () {
alert('Posted');
});
});
Solution folder path
You need to add the RequestVerificationToken header to the request.
$.ajax({
type: "POST",
headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
url: window.location.href + '?handler=DoJob',
data: {
"invNo": $('#adhocInvoiceNumber').val(),
"account": $('#invoiceAccountInput').val()
},
contentType: "application/x-www-form-urlencoded"
}).done(function (response) {
alert('Posted');
});
Documentation: https://www.learnrazorpages.com/security/request-verification#ajax-post-requests-and-json
I'm trying to post a single object data to an MVC Controler using JQuery, Below are my codes.
//declare of type Object of GroupData
var GroupData = {};
//pass each data into the object
GroupData.groupName = $('#groupName').val();
GroupData.narration = $('#narration').val();
GroupData.investmentCode = $('#investmentCode').val();
GroupData.isNew = isNewItem;
//send to server
$.ajax({
url: "/Admin/SaveContributionInvestGroup",
type: "POST",
contentType: "application/json;charset=utf-8",
dataType: "json",
data: JSON.stringify({ GroupData: JSON.stringify(GroupData) }),
success: function (res) {
alertSuccess("Success", res.Message);
//hide modal
$('#product-options').modal('hide');
hide_waiting();
},
error: function (res) {
alertError("Error", res.Message);
}
});
Below is my controller.
[HttpPost]
public JsonResult SaveContributionInvestGroup(ContributionInvestmentGroup GroupData)
{
ClsResponse response = new ClsResponse();
ClsContributionInvestmentGroup clsClsContributionInvestmentGroup = new ClsContributionInvestmentGroup();
var userID = (int)Session["userID"];
var sessionID = (Session["sessionID"]).ToString();
if (contributionGroupData != null)
{
//get the data from the cient that was passed
ContributionInvestmentGroup objData = new ContributionInvestmentGroup()
{
contributionInvestmentGroupID = 0,
groupName = GroupData.groupName,
narration = GroupData.narration,
investmentCode = GroupData.investmentCode,
isNew = GroupData.isNew
};
response = clsClsContributionInvestmentGroup.initiateNewContributionInvestmentGroup(sessionID, objData);
}
else
{
response.IsException = true;
response.IsSucess = false;
response.Message = "A system exception occurred kindly contact your Administrator.";
}
return Json(new
{
response.IsSucess,
response.Message
});
}
The issue is, the data is not been posted to the controller, the controller receives a null object.
Kindly assist, would really appreciate your effort, thanks.
Try Like this:
//send to server
$.ajax({
type: "POST",
url: "/Admin/SaveContributionInvestGroup",
dataType: "json",
data: GroupData,
success: function (res) {
alertSuccess("Success", res.Message);
//hide modal
$('#product-options').modal('hide');
hide_waiting();
},
error: function (res) {
alertError("Error", res.Message);
}
});
in your controller your dont have custom binding to bind JSON to your model thats why you get null in you parameter.
instead just post it as query, try simply changes your ajax option like so:
{
...
contentType: "application/x-www-form-urlencoded", //default:
...,
data: $.param(GroupData),
...
}
and perhaps property names are case sensitive so you will need to change your javascript model's name
I need to get the resource data on js file.
so I want to transfer the resource data from controler action to js file by ajax callback.
How to do this?
I'm working in asp.net mvc 5
I'm do it's so:
controller Action:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult GetCultureResource()
{
ResourceSet resourceSet =
Resources.Resources.ResourceManager.GetResourceSet(new System.Globalization.CultureInfo(cultureName), true, true);
var dicResource= resourceSet.Cast<DictionaryEntry>()
.ToDictionary(x => x.Key.ToString(),
x => x.Value.ToString());
var jsonString = JsonConvert.SerializeObject(dicResource);
return Json(new { resource = jsonString});
}
javascript fanction:
function SetCultureResource() {
$.ajax({
type: "POST",
url: "/ControllerName/GetCultureResource",
dataType: "json",
success: function (data) {
var obj = jQuery.parseJSON(data.resource);
//do somthing as this with Resource
//alert(Resource.BeforLogOut);
},
error: function (data) {
}
});
}
I'm using FullCalendar (http://arshaw.com/fullcalendar/) and I need help with passing data using json to a c# function in the code behind page of my ASP.net page.
I am using json to load data like so in my FullCalendar web application:
Code behind:
[WebMethod]
public static List<Event> GetEvents()
{
List<Event> events = new List<Event>();
events.Add(new Event()
{
EventID = 1,
EventName = "EventName 1",
StartDate = DateTime.Now.ToString("MM-dd-yyyy"),
EndDate = DateTime.Now.AddDays(2).ToString("MM-dd-yyyy"),
EventColor = "red"
});
events.Add(new Event()
{
EventID = 2,
EventName = "EventName 2",
StartDate = DateTime.Now.AddDays(4).ToString("MM-dd-yyyy"),
EndDate = DateTime.Now.AddDays(5).ToString("MM-dd-yyyy"),
EventColor = "green"
});
return events;
}
asp.x page:
events: function(start, end, callback)
{
$.ajax(
{
type: 'POST',
contentType: 'application/json',
data: "{}",
dataType: 'json',
url: "Calendar.aspx/GetEvents",
cache: false,
success: function (response) {
var events = $.map(response.d, function (item, i) {
var event = new Object();
event.id = item.EventID;
event.start = new Date(item.StartDate);
event.end = new Date(item.EndDate);
event.title = item.EventName;
event.color = item.EventColor;
return event;
})
callback(events);
},
error: function (err) {
alert('Error');
}
});
},
This is working fine. Now I want to save data by calling a function and passing it data. Here is what I have done so far:
Code behind:
[WebMethod]
public static bool SaveEvents(List<Event> events)
{
//iterate through the events and save to database
return true;
}
asp.x page
function save() {
var eventsFromCalendar = $('#calendar').fullCalendar('clientEvents');
var events = $.map(eventsFromCalendar, function (item, i) {
var event = new Object();
event.id = item.id;
event.start = item.start;
event.end = item.end;
event.title = item.title;
event.color = item.color;
return event;
});
$.ajax(
{
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(events), **<-- I have to pass data here but how???**
dataType: 'json',
url: "Calendar.aspx/SaveEvents",
cache: false,
success: function (response) {
alert('Events saved successfully');
},
error: function (err) {
alert('Error Saving Events');
}
});
return false;
}
The above ajax post is where I need help with. The variable events contais all the FullCalendar event info.
How do I pass the data 'events' to the function 'SaveEvents'?
I can change the SaveEvents signature if need be.
EDIT
If I change my c# function to use an array like s0:
[WebMethod]
public static bool SaveEvents(Event[] newEvents)
{
return true;
}
And pass the following data through:
data: JSON.stringify({ newEvents: events }),
Then the function 'SaveEvents' gets called with an array of size 4 but all the data values are null, why is this?
Thanks
Obvious from your code that you have a c# class as
public class Events
{
public int EventID {get; set;}
public string EventName {get;set;}
public StartDate {get; set;}
public string end {get; set;}
public string color {get; set;}
}
So take json array. A sample here
// Array which would be provided to c# method as data
var newEvents=[
{
EventID : 1,
EventName : "EventName 1",
StartDate : "2015-01-01",
EndDate : "2015-01-03",
EventColor : "red"
},
{
EventID : 2,
EventName : "EventName 2",
StartDate : "2015-01-02",
EndDate : "2015-01-04",
EventColor : "green"
}
];
Now the ajax request which passes JSON objects to posted URL
$.ajax
({
type: 'POST',
contentType: 'json',
data: {newEvents:newEvents},// Pass data as it is. Do not stringyfy
dataType: 'json',
url: "Calendar.aspx/SaveEvents"
success: function (response) {
alert('Events saved successfully');
},
error: function (err) {
alert('Error Saving Events');
}
});
Update :
To make sure that there is nothing else wrong please test your Save Events as. If it goes fine above should work as well, As it is working for me :)
[WebMethod]
public static bool SaveEvents(string EventName)
{
//iterate through the events and save to database
return true;
}
$.ajax
({
type: 'POST',
contentType: 'json',
data: {EventName:'myevet 1'},
url: "Calendar.aspx/SaveEvents",
cache: false,
success: function (response) {
alert('Events saved successfully');
},
error: function (err) {
alert('Error Saving Events');
}
});
I have a problem related the ajax call request searched for it on stack overflow tried all the related help that i got but can't solve the problem. the problem is that i request to a controller from my view using this code.
<script type="text/javascript">
$(document).ready(function () {
$('#contactDiv ').click(function() {
var number = $(this).find('.ContactNumber').text();
var dataJson = {"contactNumber": number};
$.ajax({
type: "POST",
url: "../contactWeb/messages",
data: JSON.stringify(dataJson),
//data: dataJson,
//contentType: "application/json",
contentType: "application/json",
cache: false,
success: function (msg) {
//msg for success and error.....
alert(msg);
return true;
}
});
});
});
</script>
and the controller that receives the call is
[HttpPost]
public JsonResult messages(string dataJson)
{
Int64 userID = Convert.ToInt64(Session["userId"]);
try
{
List<MessagesModel> messagesModel = new List<MessagesModel>();
IMessages MessageObject = new MessagesBLO();
messagesModel = MessageObject.GetAllMessagesWeb(userID , dataJson);
//ViewData["Data"] = messagesModel;
}
catch (Exception e)
{
}
//return View();
string msg = "Error while Uploading....";
return Json(msg, JsonRequestBehavior.AllowGet);
}
but it passes NULL value to the controller
There are couple of issues need to be fixed
whats the need of
JsonRequestBehavior.AllowGet
when your action type is post.
If you are using asp.net mvc4 use Url.Action to specify url i.e
url:"#Url.Action("ActionName","ControllerName")"
Now Talking about your issue.
Your parameter names must match, change dataJson to contactNumber.Though its ok to use there isnt any need to use JSON.stringify as you are passing single string parameter.
[HttpPost]
public JsonResult messages(string contactNumber)
{
Int64 userID = Convert.ToInt64(Session["userId"]);
Hi could you change the name of your parameters string dataJson in your action to contactNumber in respect to the object you pass via your Ajax call
[HttpPost]
public JsonResult messages(string contactNumber) //here
{
Int64 userID = Convert.ToInt64(Session["userId"]);
try
{
List<MessagesModel> messagesModel = new List<MessagesModel>();
IMessages MessageObject = new MessagesBLO();
messagesModel = MessageObject.GetAllMessagesWeb(userID , contactNumber); //and here
//ViewData["Data"] = messagesModel;
}
catch (Exception e)
{
}
//return View();
string msg = "Error while Uploading....";
return Json(msg, JsonRequestBehavior.AllowGet);
}
If you want to get JSON in messages() try this:
<script type="text/javascript">
$(document).ready(function () {
$('#contactDiv ').click(function() {
var number = $(this).find('.ContactNumber').text();
var data = {"contactNumber": number};
var dataJson = JSON.stringify(data);
$.ajax({
type: "POST",
url: "../contactWeb/messages",
dataType: 'text',
data: "dataJson=" + dataJson,
//data: dataJson,
//contentType: "application/json",
cache: false,
success: function (msg) {
//msg for success and error.....
alert(msg);
return true;
}
});
});
});
</script>