Fill jQuery Variable from serverside on load - c#

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.

Related

Jquery .post method is sending a null value. How to pass actual value to controller?

I have a controller that applies to an edit view in asp.net MVC. I have an actionlink that sends the row Id to the controller which then brings back the correct row to see in the associated view.
I then have a partial view below that. That also requires a parameter in order to bring associated data from another table.
I have a Jquery .post call that runs after the page is loaded. I can alert out and show the exact value I want to send to the controller.
$(document).ready(function () {
var url = "/Home/MmsAndNotes";
var Uc = $("#Id").serialize();
alert(Uc);
$.post(url, {Id: Uc}, function (data) {
alert("what is Uc now? " + uc); //just for testing
});
})
I have also used it this way.
$(document).ready(function () {
var url = "/Home/MmsAndNotes";
var Uc = $("#Id").val();
alert(Uc);
$.post(url, Uc, function (data) {
});
})
the alerts come up and show the value I want. However, when the .post call runs, it sends a null value. Here is my controller.
public ActionResult MmsAndNotes(string Id)
{
//Declare LogisticsVM for individual policy info
LogisticsMMS_NotesVM model;
if(uc == null)
{
return Content("uc is empty.");
}
int val = Convert.ToInt32(uc);
using (Db db = new Db())
{
LogisticsMMS_NotesDTO dto = db.LogisticsMMS.Find(val);
//confirm policy exists
if (dto == null)
{
return Content("This policy cannot be found." + val);
}
model = new LogisticsMMS_NotesVM(dto);
}
return PartialView(model);
}
It always returns as uc is empty. I repeat, when the alerts come up. I get the correct value to send to the controller. But once it sends, something happens and it converts to null. HELPPPPP.. please .. I'm losing my mind over this one.
I don't know why, but changing my $.post() call to an $.ajax({}) call solved the issue. As you can see above, I had the $.post call. Using this instead,
$.ajax({
type: "POST",
url: "/Home/MmsAndNotes",
dataType: 'text',
data: { Id: Uc }
});
Solved it. I thought Jquery's shortened calls worked the same way. They certainly might, but doing it this way was the only way it worked for me.
P.S. Thanks Tyler (above) for your comments.
this solution should be work :
$(document).ready(function () {
$.ajax({
url: '/Home/MmsAndNotes',
type: 'GET',
dataType: "html",
data: { uc : $("#Id").val() },
success: function (result) {
code here
}
});
})
You need to verify if $("#Id").val() is not empty

Iterating through list obtained via JSON using jQuery in ASP.NET MVC

I am trying to write an autocomplete feature on a page where the user can enter characters into a textbox and the dropdown will give options for addresses which it retrieves that match the characters being typed. I have a method in the controller which gets the list of customer addresses(which is what I want to show in the textbox) by connecting to the database and executing a query with Linq which looks like the following:
public ActionResult _getCustomerAddresses(int customerId)
{
return Json(theShop.getCustomerAddresses(customerId).Select(s => new { AddressID = s.AddressID, Addr = s.FirstName + ": " + s.Address1 }).ToList());
}
I then have a function in my loadAddresses method in my cshtml file which passes the currently logged in customers customerID to the _getCustomerAddresses method and looks like the following:
function loadAddresses() {
$.ajax({
type: 'post',
url: "/ShoppingCart/_getCustomerAddresses?customer=#Model.LoggedInCustomerID",
dataType: "json",
success: function (data) {
for (var line in data)
{
//Need to somehow iterate through the data list and append them to an array so I can add them to the source within autocomplete method to display them.
}
}
});
}
How do I go through this JSON list that is returned from the controller method and append them to an array for displaying? (.autocomplete function of jQuery seems to require an array for the data to display https://jqueryui.com/autocomplete/) I may need a better explanation of using JSON to help me do this
Thanks very much in advance,
Corey
you can use $.each to loop over all item return from Action
First create an empty array then push the data in it.
function loadAddresses() {
var itemsSearchItemsArray = new Array();
$.ajax({
type: 'post',
url: "/ShoppingCart/_getCustomerAddresses?customer=#Model.LoggedInCustomerID",
dataType: "json",
success: function (data) {
$.each(data,function(index,value){
itemsSearchItemsArray.push(value.Addr);
});
}
});
}
function loadAddresses() {
$.ajax({
type: 'post',
url: "/ShoppingCart/_getCustomerAddresses?customer=#Model.LoggedInCustomerID",
dataType: "json",
success: function (data) {
var myArray = JSON.parse(data.d);
}
});
}
Just use JSON.parse to get array of objects. Then you can just simply iterate over it like myArray[0].AddressID.

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

Passing object to a WebMethod through jquery ajax [duplicate]

This question already has answers here:
Pass a user defined object to ASP.NET Webmethod from jQuery, using JSON
(2 answers)
Closed 4 years ago.
I am trying to pass an object to a page method defined. I'm trying to pass data to it collected from three textboxes.
Page Method
[System.Web.Services.WebMethod]
public static string saveDataToServer(object csObj)
{
// Function Body.
}
Javascript/jQuery
$("#osmSendMsg").click(function () {
debugger;
var cntDetails = {
cntName : $("#osmContactName").val(),
cntEmail : $("#osmContactEmail").val(),
cntMsg : $("#osmContactMessage").val()
}
PostDataToServer(cntDetails,"Please wait...","/ContactUs.aspx/saveDataToServer","csObj");
});
PostDataToServer
// Post data to server (ajax call).
function PostDataToServer(dataToSend, strMessagetoShow, strMethodToCall, jsonObjectName) {
debugger;
/*
dataToSend Contains the JSON Object.
submitType 1 == Normal Submit; 2 == Submit and Print.
strMessagetoShow Text that is displayed in the Please Wait Window.
*/
var tempurl = strMethodToCall;
var tempdata;
$.ajax({
url: tempurl,
type: "POST",
async: false,
dataType: "json",
data: "{" + jsonObjectName + ":" + JSON.stringify(dataToSend) + "}",
//timeout: 30000,
contentType: "application/json; charset=utf-8",
success: function (data) {
tempdata = data;
},
error: function (result) {
tempdata = null;
}
}); //end of the ajax call
return tempdata;
} //End of the post Data
Now the call is reaching the web method. No problem. I'm getting the object as well.But how do I process the object?
As you can see, that's what I'm getting. I also tried declaring a class and passing it as the parameter..but all it's properties are empty. If you notice the data is appearing as a key, value pair. I could convert it into a Dictionary, but I believe that's a complicated solution.
A simpler solution would be welcomed!
Your result collection is being returned in the 'data' parameter of your success method. You can simply process this parameter directly like data[0].cntName.
As you are able to reach your webmethod, you need to modify your webmethod to read the data from the object as follows:
[System.Web.Services.WebMethod]
public static string saveDataToServer(Dictionary<string, string> csObj)
{
try
{
string Name = csObj["cntName"].ToString();
string Email = csObj["cntEmail"].ToString();
//you can read values like this and can do your operation
return "";//return your value
}
catch(Exception ex)
{
throw new Exception(Ex.Message);
}
}

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

Categories