How to get values from a method to ajax in .net 6 - c#

this is my jQuery code on submit button
function SubmitFilter()
{
var transactionNumb = $("#transactionNumber").val();
var cardHolderName = $("#cardHolder").val();
$.ajax({
type: "GET",
url: "https://localhost:7197/Transactions?transaction_number="+transactionNumb+"&cardholder="+cardHolderName,
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function (data)
{
alert(data);
}
});
}
And this the code behind class from here I'm not able to call the GetTransactions method directly..ajax method goes to onget method only.
Here my intention is to get the jarray value in ajax success function
you can look full code if you need in this link
https://technotesfromwork.blogspot.com/2022/07/tech-note.html
please let me know how i can change this code to return the jarray value to ajax. thanks in advance..
public void OnGet(int CurrentPage,int transaction_number, string cardholder)
{
this.Authorize = HttpContext.Session.GetString("Roles");
this.CurrentPage = CurrentPage;
if(CurrentPage==0)
{
this.CurrentPage = 1;
}
ViewData["Title"] = "Transactions List";
Transactions = GetTransactions(this.CurrentPage,transaction_number,cardholder);
}
public JArray GetTransactions(int currentPage,int transaction_number , string cardholder)
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", HttpContext.Session.GetString("JwtToken"));
var url = $"{BaseApiUrl}/transactions?page={currentPage}&limit={PageSize}";
var filters ="";
var requestUri = new Uri(url);
var responseTask = client.GetAsync(requestUri);
responseTask.Wait();
var result = responseTask.Result;
// this.TotalResults = result.Headers.GetValues("X-Paging-Pages");
this.TotalResults = "5";
if (result.IsSuccessStatusCode)
{
var reportResults = Task.Run(async() => await result.Content.ReadAsAsync<JArray>()).Result;
return reportResults;
}
}
return JArray.Parse("[]");
}

Create a handler to retrieve a JSON result for the ajax call :
public void OnGetAsJson(int CurrentPage,int transaction_number, string cardholder)
{
this.Authorize = HttpContext.Session.GetString("Roles");
this.CurrentPage = CurrentPage;
if(CurrentPage==0)
{
this.CurrentPage = 1;
}
ViewData["Title"] = "Transactions List";
var transactions = GetTransactions(this.CurrentPage,transaction_number,cardholder);
return new JsonResult(transactions);
}
and change the ajax url to this :
function SubmitFilter()
{
var transactionNumb = $("#transactionNumber").val();
var cardHolderName = $("#cardHolder").val();
$.ajax({
type: "GET",
url: "https://localhost:7197/Transactions?handler=AsJson?transaction_number="+transactionNumb+"&cardholder="+cardHolderName,
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function (data)
{
alert(data);
}
});
}

Related

Pass object via ajax to Controller is null

i'm trying pass a object to a controller, but in debug when i check data, the object arrive null. I already try to many things, but never get success.
Ajax:
function filtro() {
var nome = document.getElementById("nome").value;
var idade = document.getElementById("idade").value;
var dataCriacao = document.getElementById("data-criacao").value;
var dataInicio = document.getElementById("data-inicio").value;
var dataFim = document.getElementById("data-fim").value;
var tipo = document.getElementById("tipo").value;
var ativo = document.getElementById("ativo").checked;
var filtro = {
IdadeText: idade,
Nome: nome,
DataDestaqueInicio: dataInicio,
DataDestaqueFim: dataFim,
DataAnuncioCriacao: dataCriacao,
Ativo: ativo,
Tipo: tipo,
};
debugger
$.ajax({
type: "POST",
url: '#Url.Action("Anuncios", "Admin")',
data: filtro,
contentType: 'application/json;',
success: function (result) {
}
})
}
My controller:
[HttpPost]
public async Task<JsonResult> Anuncios(FiltroAnuncioDTO filtro,int pg = 1)
{
return Json("ok");
}
the result:
Solved removing [ClaimsAuthorize("Admin", "")]

WebApi 2 - Json request pending

when I call one webapi from ajax, if I return something different from simple string or int, the request is still pending.
here my javascript:
var endPoint = "/api/services/attivita/set";
$.ajax({
url: endPoint,
data: JSON.stringify(
{
'id': attivita.IDTipoAttivita,
'descrizione': $('#Descrizione').val()
}
),
dataType: 'json',
contentType: "application/json;charset=utf-8",
processData: false,
type: 'post',
success: function (data) {
console.log('ok');
},
error: function (data) {
console.log('ko');
}
});
and here webapi code
[System.Web.Http.HttpGet]
[System.Web.Http.HttpPost]
[System.Web.Http.Route("api/services/attivita/set")]
public TipoAttivita SetAttivita([FromBody] dynamic obj)
{
var id = (int)obj.id;
var descrizione = obj.descrizione.ToString();
var nuovo = id == -1;
var attivita = new TipoAttivita()
//do stuff of attivita object
this.CurrentDb.TipoAttivita.Add(attivita);
this.CurrentDb.SaveChanges();
return (attivita);
}
If I change to "public int...." and "return(1);" at the end of the function everything works fine.
in WebApiConfig.cs I have this
var jsonFormatter = new JsonMediaTypeFormatter
{
SerializerSettings = {ReferenceLoopHandling = ReferenceLoopHandling.Ignore}
};
jsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
config.Formatters.Clear();
config.Formatters.Add(jsonFormatter);
Any idea?
Thanks a lot
Try to change return type to IHttpActionResult and return Ok(attivita)

Displaying PDF from byte[] in MVC 4

I'm using Grid.MVC to display data from an entity model. On row click I am getting the value of a cell and passing it to my controller with a json/ajax function.
In my controller the int "ticketnumber" is passing just fine. The thing that I am not understanding is when I hard code the int, it is working (if I directly browse to http://localhost:58779/ticket/PDFVIEW).
The controller seems to be running through just fine, but it is not displaying the PDF..it just takes me back to my grid in my view with the ajax script. Thanks for the help.
Edit - Code:
<script>
$(function () {
pageGrids.TicketGrid.onRowSelect(function (e) {
var ticketnumber = e.row.UnsettledID;
ticketnumber = JSON.stringify({ 'ticketnumber': ticketnumber });
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/ticket/PDFVIEW',
data: ticketnumber,
});
});
});
</script>
controller:
[ActionName("PDFVIEW")]
[HttpGet]
public ActionResult PDFVIEW(int ticketnumber)
{
var db = new ScaleTrac_VerticalEntities();
Ticket_UnsettledScaleImages tu = new Ticket_UnsettledScaleImages();
tu = db.Ticket_UnsettledScaleImages.Where(p => p.UnsettledID == ticketnumber).First();
string filename = "ScaleTick" + tu.UnsettledID + ".pdf";
{
byte[] bytes = tu.ScaleTicket;
TempData["bytes"] = bytes;
Response.Clear();
MemoryStream ms = new MemoryStream(bytes);
return new FileStreamResult(ms, "application/pdf");
}
}
You can't use AJAX to download a file in this way. Your AJAX code is getting the contents of the PDF, but your browser needs to receive it as a normal request in order to view it. You should instead render a link to the PdfView action, or use window.setLocation if you need to do it from a Javascript event handler.
Note you'll also need to change your action method to accept HttpGet.
Using what Richard said helped a lot.
My Json I changed to:
<script>
$(function pdfviewer() {
pageGrids.TicketGrid.onRowSelect(function (e) {
var ticketnumber = e.row.UnsettledID;
ticketnumber = JSON.stringify({ 'ticketnumber': ticketnumber });
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/ticket/PDFVIEW',
data: ticketnumber,
success: function (d) {
if (d.success) {
window.location = "/Ticket/DownloadFile" + "?fName=" + d.fName;
}
},
error: function () {
alert("Error");
}
});
});
});
</script>
And in my controller I did:
[ActionName("PDFVIEW")]
public ActionResult pdf(int ticketnumber)
{
var db = new ScaleTrac_VerticalEntities();
Ticket_UnsettledScaleImages tu = new Ticket_UnsettledScaleImages();
tu = db.Ticket_UnsettledScaleImages.Where(p => p.UnsettledID == ticketnumber).First();
string filename = "ScaleTick" + tu.UnsettledID + ".pdf";
{
byte[] bytes = tu.ScaleTicket;
TempData["bytes"] = bytes;
Response.Clear();
MemoryStream ms = new MemoryStream(bytes);
var fName = string.Format("File-{0}.pdf", DateTime.Now.ToString("s"));
Session[fName] = ms;
return Json(new { success = true, fName }, JsonRequestBehavior.AllowGet);
}
}
public ActionResult DownloadFile(string fName)
{
var ms = Session[fName] as MemoryStream;
if (ms == null)
return new EmptyResult();
Session[fName] = null;
return File(ms, "application/pdf", fName);
}
Thank you very much!

JSON Invalide primitive

I want to passing my number of seat to TryJSIN.aspx in function test().
but I have error, when I use type 'GET' then I have error
"Invalid JSON primitive: 1-9."
1-9 is noSeat value.
but when I change to 'POST' I have error
An attempt was made to call the method 'test' using a POST request, which is not allowed.
please check my following code. This is when I use get type
var sid = jQuery(this).attr('id');
$.ajax({
url: "TryJSON.aspx/test",
type: "GET",
data: {noSeat: sid},
contentType: "application/json; charset=utf-8",
success: function (response) {
// var arr = JSON.parse(response.d);
console.log(arr);
},
error: function () {
alert("sorry, there was a problem!");
console.log("error");
},
complete: function () {
console.log("completed");
}
});
and this following ajax when I use POST type
var sid = jQuery(this).attr('id');
$.ajax({
url: "TryJSON.aspx/test",
type: "POST",
data: JSON.stringify({'noSeat': sid}),
contentType: "application/json; charset=utf-8",
success: function (response) {
// var arr = JSON.parse(response.d);
console.log(arr);
},
error: function () {
alert("sorry, there was a problem!");
console.log("error");
},
complete: function () {
console.log("completed");
}
});
and this is my c# code
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static string test(string noSeat)
{
return noSeat;
}
Please help me. I'm pretty new in c# ajax and jQuery. so I need a lot of help
UPDATE:
I Edit my code after first comment. but it show the same.
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static string test(string noSeat)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(noSeat).ToString();
}
When I use POST, I not allowed to use [ScriptMethod(UseHttpGet = true)] because it for GET type. then the data must use JSON.stringify when I use contentType: "application/json; charset=utf-8" because it thinks that I send JSON whereas I send string data. so I need to convert it to JSON first.
var sid = jQuery(this).attr('id');
//console.log(sid);
$.ajax({
url: "TryJSON.aspx/test",
type: "post",
data: JSON.stringify({ 'noSeat': sid }),
contentType: "application/json; charset=utf-8",
success: function (response) {
var arr = JSON.parse(response.d);
objData = new Array();
objData = arr;
for (i = 0; i < objData.length; i++)
{
alert(objData[i].noBooking +" "+ objData[i].noSeat);
}
},
error: function () {
alert("sorry, there was a problem!");
console.log("error");
},
complete: function () {
console.log("completed");
}
this is how to solve on C#
[WebMethod]
// [ScriptMethod(UseHttpGet = true)]
public static string test(string noSeat)
{
SqlConnection conn = DBConnection.getConnection();
SqlCommand cmd;
SqlDataReader dr;
conn.Open();
string sql = "Select noBooking,noSeat FROM booking WHERE noSeat = '" + noSeat +"' AND statusBooked = 1";
cmd = new SqlCommand(sql, conn);
dr = cmd.ExecuteReader();
List<booking> BookList = new List<booking>();
while (dr.Read())
{
booking bookClass = new booking();
bookClass.noBooking =(int)dr[0];
bookClass.noSeat = dr[1].ToString();
BookList.Add(bookClass);
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(BookList).ToString();
}

JQuery.Ajax and MVC4

I have a need to call a method on my controller to return a complex type using the JQuery.Ajax method.
function CallMethodTest(Id) {
//alert(Id);
$.ajax({
type: 'POST',
url: '/MyController/MyMethod',
dataType: "json",
contentType: "application/json; charset=utf-8",
//data: "{'Id': '" + Id + "'}",
success: function (data) {
alert(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
[System.Web.Services.WebMethod]
public string MyMethod()
{
return "ABC"; // Gives me the error on the first alert of "200" and the second alert "Syntax Error: Invalid Character"
return "1"; // Works fine
}
As the code explains, if I return an integer (as a string) the return works and I alert "1", however, If I try and return any alpha characters I get the alerts shown in the comments of MyMethod.
From your code, it looks as though you are returning the value from your Controller url: "/MyController/MyMethod"
If you are returning the value from your controller, then get rid of the [System.Web.Services.WebMethod] code and replace it with this ActionResult
[HttpPost]
public ActionResult MyMethod(){
return Json("ABC");
}
Also, if you are ever going to call a method in your controller via GET then use
public ActionResult MyMethod(){
return Json("ABC", JsonRequestBehavior.AllowGet);
}
In View You use the following code,
function ItemCapacity() {
$.ajax({
type: "POST",
url: '#Url.Action("ItemCapacityList", "SalesDept")',
data: { 'itemCategoryId': itemCategoryIds },
dataType: 'json',
cache: false,
success: function (data) {
var capacityCounter = 0;
var capacitySelected = "";
for (var i = 0; i < rowsCount; i++) {
var tr = $("#gvSpareSetItemsDetails tbody tr:eq(" + i + ")");
var categoryId = $(tr).find('td:eq(5)').text();
var isSelectOrNot = $(tr).find('td:eq(1)').find('select');
if (isSelectOrNot.is('select')) {
$.map(data, function (item) {
if (categoryId == item.ItemCategoryID) {
isSelectOrNot.get(0).options[isSelectOrNot.get(0).options.length] = new Option(item.CapacityDescription, item.ItemCapacityID);
capacityCounter = capacityCounter + 1;
capacitySelected = item.ItemCapacityID;
}
});
if (capacityCounter == 1) {
isSelectOrNot.val(capacitySelected);
}
capacityCounter = 0;
capacitySelected = "";
}
}
},
error: function () { alert("Connection Failed. Please Try Again"); }
});
}
}
In the Controller Use the following Code,
public JsonResult ItemCapacityList(string itemCategoryId)
{
List<ItemCapacity> lsItemCapacity = new List<ItemCapacity>();
string[] itemCategory = itemCategoryId.Split('#');
int itemCategoryLength = itemCategory.Length, rowCount = 0;
string itemCategoryIds = string.Empty;
for (rowCount = 0; rowCount < itemCategoryLength; rowCount++)
{
itemCategoryIds += "'" + itemCategory[rowCount].Trim() + "',";
}
itemCategoryIds = itemCategoryIds.Remove(itemCategoryIds.Length - 1);
lsItemCapacity = salesDal.ReadItemCapacityByCategoryId(itemCategoryIds);
return new JsonResult { Data = lsItemCapacity };
}

Categories

Resources