Passing an array from javascript to code behind - C# - 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".

Related

Calling method from javascript in MVC

I want to call a controller method from Javascript. I used the following code:
<input type="submit" name="button" value="Run" onclick="RunEXE"/>
I want to write the javascript to call the below function in controller.
public void Run(UserProgram userProgram)
{
SaveAndCompile(userProgram);
}
Can anyone provide me the javascript to call the function.
You can't just call a function like that. What you need to understand is that javascript runs on the client, and your function is on the server. What you need to do is make a request to the server, just like you would when loading a page, so for this you need an Action (make sure it is a POST action as we will be "posting" the request). This action can be as short as just calling the function you need:
[HttpPost]
public ActionResult RunAction(string option1)
{
//if needed, you can use the "option1" value to determine the UserProgram to pass
UserProgram userProgram = new UserProgram();
Run(userProgram);
//you can return a JSON reuslt that you can evaluate back at the client
return Json(new { #Success = true, #MyString = "a string" });
}
Then you want to use ajax to call the function from the client (javascript), for this I would recommend JQuery as it makes things much easier using post:
$.post('#Url.Action("RunAction", "MyController")',
{
option1: "some optional value"
},
function (data) {
alert("success!");
//here you have access to your JSON result via data, for example:
//data.Success = true
//data.MyString = "a string"
}
);
You can use Ajax here. jQuery ajax is very flexible and easy
Then
prepare your data to post
var myData={};// this is similar to your C# class UserProgram structure
myData.property1=value1; //etc
jQuery.ajax{(
url: '/controllerName/Run/', // or '#Url.Action("Run", "ControllerName")'
type: 'post',
data:{userProgram:myData},
success: function (data) { jQuery('#container').html(data); }
)};
or shorthand
$.post('/controllerName/Run/',{userProgram:myData}, function(result){});
Try this using JQuery:
function RunEXE() {
$.post('#Url.Action("Run", "ControllerName")',
{
userProgram: "WhatEver" //The parameter you want to pass to your action
},
function (data) {
//Code for what to do with the result.
})
};
Use the Normal AJAX method as::
On the Server side(i.e. In Controller) you are using some class/Model like 'UserProgram'
I don't know what are the Properties in that class but I have assumed it as::
public class UserProgram
{
public long ID{get;set}
public string Name{get;set}
}
this Model fields should be based on your Model that you have to pass into your AJAX code as::
var myData={ID:1,Name:"RJ"};
$.ajax{(
type: 'post',
url: '/controllerName/Run'
data:{UserProgram:myData},
success: function (data) {
$('#container').empty();
$('#container').html(data);
}
)};
To get the full description on using ajax calls in ASP.net MVC using jQuery please refer to:
http://bobcravens.com/2009/11/ajax-calls-to-asp-net-mvc-action-methods-using-jquery/

Ajax call to use JSON data in UserControl.ascx

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.

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).

jquery AJAX sent data in key value pair

In my aspx page, i have the js like this :-
<script language="javascript" type="text/javascript">
$("#btnLoad").click(function () {
var dataForAjax = "{'datakey':'hello'}"
$.ajax({
type: "POST",
url: "Ajax__Demo.aspx/SendFile",
data: dataForAjax,
success: function (msg) {
alert(msg); // Problem with this line. It is not showing the value.
}
});
});
</script>
In the same webpage code behind class file ,i have the webmethod defined like this:-
[WebMethod]
public static string SendFile(string key, string data)
{
return data;
}
For some reason, i am able to get the data in the alert used on the html side. alert(msg); is giving me nothing and i am expecting to get the passed value back. In this case it should be 'Hello'.
I am missing something very small here, please help me out here.
Alter these.
The AJAX Call
$(document).ready(function () {
$("#btnLoad").click(function (evt) {
var dataForAjax = "{'datakey':'hello'}";
$.ajax({
contentType: "application/json",
data: dataForAjax,
type: "POST",
url: 'Test1.aspx/SendFile',
success: function (msg) {
var msg = msg.hasOwnProperty("d") ? msg.d : msg;
alert(msg.datakey);
}
});
evt.preventDefault();
});
});
The WebMethod
[WebMethod]
public static object SendFile(string datakey)
{
return new
{
datakey = datakey
};
}
Hope this helps.
Update:
`evt.preventDefault is for preventing postback in case your control was something like input type="submit" or asp:Button
.d is ASP.NET 3.5+ feature to prevent XSS vulnerability. ( link here )
The return type is object for the web method for automatic serialization ( link here )
Also you could omitdataType in $.ajax call but contentType is an absolute necessity ( link here )
This:
var dataForAjax = "{'datakey':'hello'}"
Should be:
var dataForAjax = {'datakey':'hello'}
AJAX does not (by default anyway) send json - it sends FORM INPUT elements! jQuery is nice and will convert javascript objects into that for you.
If you really need to you can send json, but I really doubt you do, it's rare to do that.
When you send data to method you must send apropriate key-value pairs, using object in Javascript.
Examle for you method:
<script language="javascript" type="text/javascript">
$("#btnLoad").click(function () {
var dataForAjax = {'key' :'datakey', 'data' : 'hello'};
$.ajax({
type: "POST",
url: "Ajax__Demo.aspx/SendFile",
data: dataForAjax,
success: function (msg) {
alert(msg); // Problem with this line. It is not showing the value.
}
});
});

Categories