Ajax call to use JSON data in UserControl.ascx - c#

I have a usercontrol in a VisualWebPart project.I want to have an ajax call to get a json data and use it in a Jquery plugin.
in simple web applications I use a webservice that returns JSON data and call It in my pages via Ajax,that sounds like I cant use webservices and even Web Methods in my .ascx control,so how can I call a method in my UserControl to get JSON data.
EDIT: I have this code and I want to do this in a UserControl ,too.
in WebService:
public class getTimeLineService : System.Web.Services.WebService
{
[WebMethod]
public String getJsonTimeLine()
{
List<TimeLine> list = new List<TimeLine> { new TimeLine { headline = "Vine", text = "<p>Vine Test</p>", startDate = "1391,12,12", endDate = "1392,1,27" }, new TimeLine { headline = "Sh*t Politicians Say", text = "<p>In true political fashion, his character rattles off common jargon heard from people running for office.</p>", startDate = "1392,1,26", endDate = "1392,1,27" } };
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
StringBuilder sb = new StringBuilder();
serializer.Serialize(list, sb);
return sb.ToString();
}
}
and consume this WebService by ajax:
$.ajax({
type: "POST",
url: "getTimeLineService.asmx/getJsonTimeLine",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var jsonDate = eval( data.d );
},
failure: function (msg) {
alert(msg);
}
});

You can call a webmethod on the page and have the page's method pull from the server code. You could set a session value in the control and pull from that via your webmethod. As controls aren't pages, they're not actually serving anything, only being rendered.
As your using a static webmethod, you'll need to use HttpContext to get your session data.
http://msdn.microsoft.com/en-us/library/system.web.httpcontext.session.aspx
Edit
Store your data from the user control in session:
Session["MyData"] = myDataObj;
You can access Session through your WebMethod this way:
var myRetrievedDataObj = HttpContext.Session["MyData"];
You can return serialized JSON from server objects and collections using the JavaScriptSerialzer class. http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx
You then return that string to your AJAX call and you have your JSON data.

Related

Passing an array from javascript to code behind - C#

In my website, i'm declaring an array in javascript and insert them elements dynamically. So now, I want use that array from my C# code. I don't want use ajax to send that element to an web service... I just want use an C# event, like OnClick and access the array that was build in javascript.
I searched for an answer but I just found the oposite.
Thanks
The easiest way is AJAX call and i don't understand why you are avoiding that ?
Make an AJAX call from your button click.
look here a demo :
Ajax call is not calling to the server side and in httpfox shows error as "Error loading content (NS_ERROR_DOCUMENT_NOT_CACHED)" in ajax post call
for example : covert your array to a json string and call a web client in your c# code. Here i have a button . on button click i want to send my GRIDVIEW data to c# method(web method).
you need to remember that while sending json data using stringfy() method,
in server side we need to define the parameter as object.
not any other format like string/int/bla bla.....
use Scripts/jquery-1.8.3.min.js
http://code.jquery.com/ui/1.10.3/jquery-ui.js
$('#btnResult').on('click', function () {
var mydata = [];
$("#<%=GridProjectDetails.ClientID %> tr").each(function () {
var myObject = new Object();
var id = $(this).find("input[name*='ID']").val();
var locationcode = $(this).find("input[name*='TextLocationCode']").val();
var Location = $(this).find("input[name*='TextLocation']").val();
myObject.id = id;
myObject.locationcode = locationcode;
myObject.Location = Location;
mydata.push(myObject);
});
var myString = JSON.stringify({ details: JSON.stringify(mydata) });
alert(myString);
var exportdata = myString;
$.ajax({
type: "POST",
url: "Default.aspx/ExportToExcel",
data: exportdata,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#Result").text(data.d);
},
error: function () { alert(arguments[2]); }
});
});
});
and server side method should be
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string ExportToExcel(object details)
{
return "Message : Success";
}
It's a kinda weird thing to do, but if you have to do it, you can do it by creating a form, inside the form have a hidden text field and call a function when submitting to update the value of this field.
The markup:
<form id="yourForm" method="post" >
<input type="text" name="hiddenFieldName" id="hiddenFieldName" hidden="hidden" />
</form>
The javascript:
void yourProcedure() {
var yourArray = ["Value1", "Value2", "Value3", "Value4"];
document.getElementById('hiddenFieldName').value = yourArray.join();
document.getElementById("yourForm").submit();
}
Then in the server, the form variable will contain "Value1,Value2,Value3,Value4".

Fill jQuery Variable from serverside on load

I was looking on internet for over 2 hrs now, trying to find simple example of how to fill jQuery Variable from serverside code on load of asp.net page.
What i have so far:
I have a button which call this jquery code:
function GetListOfQuestions() {
$.ajax({
type: "POST",
url: 'UserProfile.aspx/getQuestions',
contentType: "application/json; charset=utf-8",
dataType: "json",
error: OnAjaxError,
success: AjaxSucceeded
});
//$.getJSON('UserProfile.aspx/getQuestions', {}, function (data) {
// alert(data);
//});
}
function AjaxSucceeded(result) {
alert(result);
}
GetListOfQuestions calls serverside :
[WebMethod]
public static List<Question> getQuestions(){
var userGuid = (Guid)System.Web.Security.Membership.GetUser().ProviderUserKey;
IEnumerable<Question> list = Question.getQuestionsForUser(userGuid).Select(x => new Question
{
Uid = x.Uid,
Content = x.Content
});
return list.ToList();
}
result return an object if I alert it, so it must contain some kind of data, but I can't find any example of how I can retrieve data again on client side.
I'm not sure if what I am doing right now is right at all (I'm new to jQuery). So how can I retrieve data from result variable again?
There could be better ways but this is one way I know of:
[WebMethod]
public static string getQuestions(){
var userGuid = (Guid)System.Web.Security.Membership.GetUser().ProviderUserKey;
IEnumerable<Question> list = Question.getQuestionsForUser(userGuid).Select(x => new Question
{
Uid = x.Uid,
Content = x.Content
});
return new JavaScriptSerializer().Serialize(list.ToList())
}
In your jQuery method, you can
result = $.parseJSON(data) ;
Do a console.log(result) to see how to iterate through result, should be just a for loop.
Put a hidden field on your page an set the variable value there, later read the hidden value from js.
Another option is to use ScriptManager.RegisterStart UpScript to write your variable directly as js to the page.

display json data from controller inside view

Inside my controller there is JsonResult action which returns me a list of House object.
I want onclick using ajax to retrieve these data and to display json data inside my view.
Inside firebug I'm able to see proper Response and Json result but I dont know how to display inside my view.
function GetTabData(xdata) {
$.ajax({
url: ('/Home/GetTabData'),
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ id: xdata }),
success: function (result) {
// tried with these but it doesnt work
// result = jQuery.parseJSON(result);
// alert(result.Title);
},
error: function () { alert("error"); }
});
}
public JsonResult GetTabData()
{
...
var temp = getMyData...
return Json(temp, JsonRequestBehavior.AllowGet);
}
// View page
<div id="showContent">
// Json data should appear here
</div>
Inside firebug JSON tab when success:function(result) is empty
I have following data:
Id 149
PropertyType "Apartment"
StreetNumber "202B"
CityName "Sidney"
Title "My test data"
success: function (json) {
var data = null;
$.each(json.items,function(item,i){
data = '<div>'+item.Id+ ' ' + item.CityName +'</div>';
$("#showContent").append(data);
});
}
First of all, you can specify the dataType attribute in your ajax call to 'json' and then don't have to decode the json response again -
dataType: 'json'
Then, you don't need to use parseJSON. Simply use result.Title etc.
success: function (result) {
alert(result.Title);
var showContent = $('#showContent');
showContent.html(result.Id+','+result.Title);
},
EDIT: As Mukesh said, you can have the ajax function return json without using any extra decoding.
The ajax call result is already an object. You can do whatever you want with it it inside the success function.
For example you could create a table of the information dynamically inside the function, or send the data to another function by calling the function inside that success function. Once you leave the success function, the data is not usable anymore.
Access the data object like any object (data.someProperty).

Passing unstructured JSON between jQuery and MVC Controller Actions

There is quite a lot of helpful information on MVC model binding.
My problem stems from the fact that I am trying to avoid creating strongly typed data in my MVC application as it mostly needs to act as a data router.
Basically, I have a set of fields on a page, with a class 'input', that I can gather with jQuery('.input'), iterate over and stuff into a javascript object. I then send this to my ASP.NET MVC controller:
var inputData = my_serialize( $('input');
$.ajax({
type:'POST',
url: '/acme/Ajax/CaptureInput',
dataType: "json",
data: { inputData: JSON.stringify(inputData) },
success: Page_Response_RegisterAndDeposit,
error: Page_AjaxError
});
On the C# side, I have
public JsonResult CaptureInput(string inputDataAsJsonString)
{
JavaScriptSerializer JSON = new JavaScriptSerializer();
object inputData = JSON.DeserializeObject(inputDataAsJsonString);
This seems like a wasteful level of indirection, I'd prefer to pass the data as contentType:application/json and have CaptureInput accept an object or IDictionary or even a dynamic.
You could use the serializeArray method. Let's suppose that you have a form containing the input elements which could be of any type and you want to invoke the following controller action:
public ActionResult CaptureInput(Dictionary<string, string> values)
{
...
}
here's how you could proceed:
<script type="text/javascript">
var values = $('form').serializeArray();
var data = {};
$.each(values, function (index, value) {
data['[' + index + '].key'] = value.name;
data['[' + index + '].value'] = value.value;
});
$.ajax({
url: '#Url.Action("CaptureInput")',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(data),
success: function (result) {
alert('success');
}
});
</script>
Not exactly what you're after but maybe the resolution of this issue would give you a partial workaround, by allowing you to bind to a simple wrapper object with an embedded Dictionary. It might even allow binding direct to a Dictionary. Not sure...
You might also need to explicitly set the json ContentType header in your $.ajax call
"JSON model binding for IDictionary<> in ASP.NET MVC/WebAPI"

Basic Simple Asp.net + jQuery + JSON example

I'm trying to learn how to make a simple call to the server from Javascript/jQuery. I've been trying to learn and could not find a tutorial with those simple steps.
I want to send a message to the server with two parameters (a DateTime and a String) and get back a DateTime. I want to do that via JSON.
How would the code in the server look like (structure only)?
Is there something special I should do on the server side? And how about security?
How would I implement the call in jQuery?
And how would I handle the result?
I'm most interested on code structure.
Update
I found the answer below great to get me started. However, I recently stumbled upon Full ASP.NET, LINQ, jQuery, JSON, Ajax Tutorial. It's just a fantastic and very didactic step-by-step that I want to share with anyone else who comes across this question in the future.
There are several ways that you can do this; this will serve as a single example.
You could write something like this for your jQuery code:
urlToHandler = 'handler.ashx';
jsonData = '{ "dateStamp":"2010/01/01", "stringParam": "hello" }';
$.ajax({
url: urlToHandler,
data: jsonData,
dataType: 'json',
type: 'POST',
contentType: 'application/json',
success: function(data) {
setAutocompleteData(data.responseDateTime);
},
error: function(data, status, jqXHR) {
alert('There was an error.');
}
}); // end $.ajax
Next, you need to create a "generic handler" in your ASP.net project. In your generic handler, use Request.Form to read the values passed in as json. The code for your generic handler could look something like this:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class handler : IHttpHandler , System.Web.SessionState.IReadOnlySessionState
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";
DateTime dateStamp = DateTime.Parse((string)Request.Form["dateStamp"]);
string stringParam = (string)Request.Form["stringParam"];
// Your logic here
string json = "{ \"responseDateTime\": \"hello hello there!\" }";
context.Response.Write(json);
}
See how this work out. It will get you started!
Update: I posted this code at the CodeReview StackExchange: https://codereview.stackexchange.com/questions/3208/basic-simple-asp-net-jquery-json-example
If you are using jQuery you could do it with a GET or POST.
$.get ('<url to the service>',
{ dateParam: date, stringParam: 'teststring' },
function(data) {
// your JSON is in data
}
);
$.post ('<url to the service>',
{ dateParam: date, stringParam: 'teststring' },
function(data) {
// your JSON is in data
}
);
Note that the name of the parameters in (e.g. dateParam, stringParam) need to be the same as the name of the parameters your service method is expecting. Also that your service will need to format the result as JSON, the data parameter in the call back will contain anything your service sends back (e.g. text, xml, json, etc).
See the jQuery documentation for $.ajax, $.get, $.post: http://api.jquery.com/jQuery.ajax/, http://api.jquery.com/jQuery.get/, http://api.jquery.com/jQuery.post/
Here sample code using jquery ajax call and on serverside webmethod returns jSon format data.
Jquery :
$(‘#myButton’).on(‘click’,function(){
var aData= [];
aData[0] = “2010”;
aData[0]=””
var jsonData = JSON.stringify({ aData:aData});
$.ajax({
type: "POST",
url: "Ajax_function/myfunction.asmx/getListOfCars", //getListOfCars is my webmethod
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: "json", // dataType is json format
success: OnSuccess,
error: OnErrorCall
});
function OnSuccess(response.d)) {
console.log(response.d)
}
function OnErrorCall(response)) { console.log(error); }
});
Codebehind : Here a webmethod which is returning json format data i.e list of cars
[webmethod]
public List<Cars> getListOfCars(list<string> aData)
{
SqlDataReader dr;
List<Cars> carList = new List<Cars>();
using (SqlConnection con = new SqlConnection(cn.ConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "spGetCars";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
cmd.Parameters.AddWithValue("#makeYear", aData[0]);
con.Open();
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.HasRows)
{
while (dr.Read())
{
string carname=dr[“carName”].toString();
string carrating=dr[“carRating”].toString();
string makingyear=dr[“carYear”].toString();
carList .Add(new Cars{carName=carname,carRating=carrating,carYear=makingyear});
}
}
}
}
return carList
}
//Created a class
Public class Cars {
public string carName;
public string carRating;
public string carYear;
}

Categories