How to retrieve JSON objects from ASP.NET Web Form - asp.net

I am passing JSON data to asp.net web form in script. How can I retrieve the id and use in web form
$.ajax({
type: "GET",
url: 'Edit.aspx',
cache: false,
data: ({
id: id,
page: lastDirecotry
}),
success: function (data) {
$("#dialog").html(data);
$("#dialog").dialog("open");
}
});

This is the key piece of information:
type: "GET"
Since this is a GET request, the data is going to be query string key/value pairs. So if this is the data being sent:
{ id: id, page: lastDirecotry }
Then you can get those values server-side from here:
var id = Request.QueryString["id"];
var page = Request.QueryString["page"];

in success method you can get data.id to fetch id ,and to fetch page parameter data.page will give you lastDirectory

Related

How do I fill a Javascript var with Json data from a Controller in Asp.net Core

I have a controller that returns a JsonResult
[HttpGet]
public JsonResult ShopMarkers()
{
var shops = repository.Shops;
return Json(shops);
}
In my view I'd like to fill a var with the data from that method. In an older MVC project I remember I'd write an ajax call to fill the var. Something like this:
var markers;
$.ajax({
type: 'POST',
url: '/Map/ShopMarkers',
dataType: 'json',
contentType: dataType,
data: data,
success: function (result) {
markers = result;
}
});
Or I could return a string to a view and Json.Parse it there inside a script tag.
Neither of these seem right. Is there a better way to fill my var in .Net Core?
Your client code is currently making the ajax call with POST type request. But your action method is decorated with HttpGet. So you should be getting a 404 error (If you inspect your browser dev tools, you should be able to see the status of the network (ajax) call)
[HttpPost]
public JsonResult ShopMarkers()
{
var shops = repository.Shops;
return Json(shops);
}
This should work assuming your code inside ShopMarkers method is not crashing ! (throwing any exceptions or so)
In your client side code you are trying to send an object. If you are sending a complex object, you should specify the contentType as "application/json" and send the data using JSON.stringify method.
var dataType = "application/json";
var data = { userId: 12, Password: 'ss' };
$.ajax({
type: 'POST',
url: '/Home/ShopMarkers',
dataType: 'json', // not really needed in your case
contentType: dataType,
data: JSON.stringify(data),
success: function (result) {
var markers = result;
console.log(result);
//Use result only here. Not outside
}
});
Since the ajax call is sending data in the request body, you should decorate the method parameter with [FromBody] attribute so that model binder will be able to map the posted data (from the request body) to your parameter.
[HttpPost]
public JsonResult ShopMarkers([FromBody] YourUserViewModel model)
{
//to do : Return some JSON
}

How can i retrive session from asp.net using Jquery

How can I retrieve session variable stored in a.aspx using Jquery? I have username stored in the session, I need to retrieve the session to display the username in the menu bar.
A person login through A.aspx and his details has to be displayed(from database) in B.aspx
One way to handle this would be to create a Web Method or similar within your current page so that you could access the updated value of the Session via an AJAX call :
[WebMethod]
public static string GetSessionValue(string key)
{
return Session[key];
}
Then you could make a POST call via AJAX to request the specific key that you needed (or you could ignore any parameters and simply hard-code the key that you wanted to pull within the method itself) :
public static string GetSessionDisplayName()
{
// Use the name of your Session key here to retrieve your info
return Session["DisplayName"];
}
And then you could use the following jQuery code to pull it with a parameter :
$.ajax({
type: "POST",
url: "YourPage.aspx/GetSessionValue",
data: '{ key: "your-session-key" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
// data will hold your Session value, use it here
alert(data);
}
});
Or without one :
$.post('YourPage.aspx/GetSessionDisplayName',function(data){
// data will hold your Session value, use it here
alert(data);
});

How to get post data as json in asp.net?

I am making an ajax request to my API but my API expects raw json data to parse its own objects in C# how do I get the raw Json data in C#? from the "HttpContext.Current.Request"
Here is my request:
$.ajax({
url: '/REST/GetResponse.cshtml',
type: "POST",
contentType: "Application/JSON",
data: {
code: "login",
data: {
username: $("#login_username").val(),
password: $("#login_password").val(),
rememberMe: $("#rememberMe").val()
}
},
success: function (result) {
},
error: function (result) {
console.log(result);
}
});
You should be able to get body of the request using property 'HttpRequest.InputStream`. The type of the property is a stream, but you can see an example on MSDN on how to convert it to string.
Depending of what is your underlying framework there can be easier ways to get the body. E.g. MVC of Web API use binding to map incoming requests to objects, so it might be an option to consider.

jquery-ajax post values to http-generic-handler don't return anything

I have a generic-http-handler and I am calling it from jQuery.
My handler only insert values in database but does not return anything.
I am calling the handler as follow
function InsertAnswerLog(url) {
$.ajax({
type: "POST",
url: "../Services/Handler.ashx",
data: { 'Url': url, 'LogType': "logtype" },
success: function (data) {
},
error: function (Error) {
}
});
}
Everything is working fine for me.
But is it the best way to post the values to the server.
Or can I use it in a better way.
it seems the type of data you are sending is JSON encoded try serializing the data in this form before sending and then on the server side you should encode the data before sending it back.
serializing before sending to server
function InsertAnswerLog(url) {
var DatatoSend = { 'Url': url, 'LogType': "logtype" } ;
$.ajax({
type: "POST",
url: "../Services/Handler.ashx",
data: {Jsondata: JSON.stringify(DatatoSend)},
success: function (data) {
},
error: function (Error) {
}
});
}
now on the sever side scipt
// NB: i use PHP not asp.net but it think it should be something like
Json.decode(Jsondata);
// do what you want to do with the data
// to send response back to page
Json.encode(Resonponse);
// then you could in php echo or equivalent in asp send out the data
It is important that you decode the json data on the server-side script and when a response is to be sent it should be encoded back it JSON form for it to be understood as a returned json data.
I hope this helps.

How to pass parameter back from asp.net web service if an insert to a database was successful? ASP.NET/jQuery/AJAX/JSON

I have a web form and I use jQuery/AJAX/JSON to send objects to a web service using:
$.ajax({
type: "POST",
url: "SynchroniseCustomers.asmx/synchroniseCustomers",
data: JSON.stringify(customerObj),
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (xhr, status) {},
success: function (msg) {}
});
From the web service I want to check if the insert into the database was successfull, return a variable with an ID and pass this ID to a function. In the object I have the ID so I could have:
success: function (msg) {deleteCustomer(ID);}
But this only checks if the data was passed to my method in the web service?
I have followed this example
http://encosia.com/2009/04/07/using-complex-types-to-make-calling-services-less-complex/
and in the class Person I get a message back from the database server telling me if the insert was successfull or not so like:
if (successfull)
{
return ID;
}
Is there a way to get this ID back to the web form and use this in a variable?
Thanks in advance.
You want to return a result object with an isSuccess and id property. You can then do the following:
success: function (result) {
if (!result.isSuccess) {
// display friendly error message indicating that the db insert failed
} else {
var id = result.id;
// do client side processing with primary key returned from db insert
}
}
How you return the result object depends on your web services framework (e.g., WCF, MVC, WebMethod, etc.). The framework will serialize your .NET object to a JSON encoded result (e.g., { isSuccess: true, id: '1234'}).
As an example, in ASP.NET MVC you simply return a JsonResult using Json.(MySerializableResult). If you post what you are using for web services, I'm sure you'll get a specific answer to that framework.

Resources