Retrieve value from webservice called from javascript? - c#

Is it possible to retrieve value or date from calling a webmethode from javascript, here is a sample code:
//This method is in a webservice.asmx file.
[WebMethod]
public List<tbl_City> GetAllCitiesByCountry(int countryID)
{
return Cities.GetAllCitiesByCountry(CountryID: countryID);
}
<script language="javascript" type="text/javascript">
function fillCities() {
var dropDownList = document.getElementById('<%=DropDownList_Country.ClientID %>');
var selectedIndex = dropDownList.selectedIndex;
var value = dropDownList[selectedIndex].value;
WebService.GetAllCitiesByCountry(parseInt(value.toString()), onSuccess, null, "");
}
function onSuccess(result){
alert(result[0].(PropertyName));
}
The variable x doesn't retrieve anything and I guess that it produce an error. I have tried to define an array but still it didn't work. Any idea ?
Edit:
The above code have been altered and is now an answer to my question along with the answer below which used JQuery.

Use Json response with Jquery, Its realy cool and easy.
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[ScriptService]
public class CitiService : WebService
{
[WebMethod, ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<tbl_City> GetAllCitiesByCountry(int countryID)
{
List<tbl_City> cities = GetCities(countryID);
JavaScriptSerializer js = new JavaScriptSerializer();
var jsonObj = js.Serialize(cities);
Context.Response.Clear();
Context.Response.Write(jsonObj);
Context.Response.End();
}
}
on ASp.net page
<script language="javascript" type="text/javascript">
$.ajax({
url: '<%= ResolveClientUrl("~/CitiService.asmx/GetAllCitiesByCountry") %>',
dataType: "json",
data: "{countryID:'100'}",
success: function (result) {
alert(result.d.tbl_City.Length) // loop here i.e. foreach to insert in to grid
}
});

you can do this easily with JQuery and ASP.NET webmethods Encosia

You need to register your web service with ScriptManager and then call it from the client side. Take a look on this tutorial:
Client-Side Web Service Calls with AJAX Extensions
Also you can use web service with jQuery but in this case you need to switch to JSON: Calling ASMX from jQuery

Related

Ajax call to C# webservice returns object within an object?

I have the following C# webservice (for testing purposes), which I eventually will turn into a WCFWebservice.
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[ScriptService]
public class Albums : WebService {
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public Person GetPeople() {
return new Person("Mike", 12);
}
}
And I call this using the following js:
$(document).ready(function () {
$.ajax({
url: '/webservice/Albums.asmx/GetPeople',
contentType: "application/json; charset=utf-8;",
dataType: "json",
type: 'post',
success: function (data) {
console.log(data);
}
});
});
But the weird thing (to me) is, I can't access data.Name within success().
Somehow, it adds a object d to data.
So if I want to access the name, I need to use: data.d.Name.
Where does this d come from?
It is nothing to worry about. It comes from using the OData protocol on the server:
This pattern ensures JSON payloads returned from OData services are
valid JSON statements, but not valid JavaScript statements. This
prevents an OData JSON response from being executed as the result of a
cross site scripting (XSS) attack.
To find out the nitty-gritty, see http://www.odata.org/documentation/odata-version-2-0/json-format.
This is done by default for both OData formatting and also as an security measure. You can easily remove this by adding the following to the ScriptMethod:
BodyStyle = WebMessageBodyStyle.Bare

Fill jquery array with server array?

on controller I have MODEL
public partial class CategoryModel
{
...
public int[] SelectedCustomerIds { get; set; }
}
passed to a View from a controller. How can i fill the jquery array by the Model.SelectedCustomerIds
<script type="text/javascript">
var selectedIds = []; << what to replace here
what you can do is u can first create object in jQuery and make a ajax call to server using AJAX and server side you will get tht object and you can simply transfer that object value to your model value!!
$.ajax({
type: "GET", //GET or POST or PUT or DELETE verb
url: ajaxUrl, // Location of the service
data: yourObject, //Data sent to server
contentType: "", // content type sent to server
dataType: "json", //Expected data format from server
processdata: true, //True or False
success: function (json) {//On Successful service call
var result = json.name;
$("#dvAjax").html(result);
},
error: ServiceFailed // When Service call fails
});
server side
using System.Web.Services;
[WebMethod()]
//[ScriptMethod()]
public static void SendMessage(CategoryModel yourModelObject )
{
}
You can use JSON.NET
<script type="text/javascript">
var selectedIds = #Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model.SelectedCustomerIds))
If you want to use JavaScript side array pushing, then try this
in view put all array elements in hidden
#Html.Hidden("SelectedCustomerIds_"+i, Model.SelectedCustomerIds[i])
and in JavaScript
var selectedCustomerIds = [];
$('*[id*=SelectedCustomerIds_]').each(function () {
selectedCustomerIds.push($(this).val());
});
});

Call a class in javascript in visual studio

I have a controller class that I get data from database and return it in a function, Now I want to call this function in a js and set the data in variables to show in a page:
My code looks like: exampleController.cs
namespace iSee.WebApiHse.Controllers
{
public class expController : StandardController
{
public expController(
first myService,
ISystemSettings systemSettings,
IService myExpService)
{
_myService = MyService;
_systemSettings = systemSettings;
_myExpService = myExpService;
}
// GET data
public ActionResult Myexample(int id)
{
var elementIds = _systemSettings.ExpIds;
var myElements = CacheService.AllVisibleElements
.Where(x => elementIds.Contains(x.Id)).ToList();
var container = _kpiContainerService.Find(id);
var result = _myService.MonthByContainer(myElements, container);
return AsJson(result);
}
}
}
This works and I get the data. Now I have myExp.js that I need to use these data in it. How can I do that?
Thanks
You need to execute $ajax(..) (jquery syntax) request to your controller to pass and get compute information from the server.
For this your controller method, that you're going to call, has to be exposed for HTTP access.
More details on :
How to call controller method from javascript
Do you want work with your controller in View by JavaScript? It isn't good idea. You should pass Model to View and work with it or ajax and recieve json-data
An example that uses jQuery-ajax to call your C# method:
// javascript
var id = 987;
$.ajax({
url : '/expController/Myexample/',
type : 'GET',
data { id : id },
dataType : 'json', // <-- tell jQuery to decode the JSON automatically
success : function(response){
console.log(response);
}
});
This would call your method, passing in the value of id, then it would decode the JSON into the response object.
For plain Javascript ajax (no jQuery) see MDN Ajax.
You need to make a request to the Action Myexample. Usually this is done via AJAX:
In your view you could have:
function makeAJaxCall(idToSend) {
$.ajax({
url: '#Url.Action("exp", "Myexample")',
data: { id : idToSend },
type: "POST",
success: function(data) {
$("#HTMLElement").val(data.YourData);
}
});
}
Your response will come back in the data variable if the AJAX call succeeds. I have provided an example to show you how to change the value of an HTML element with the ID HTMLElement.
To invoke the function you can do:
makeAjaxCall(100);
You may load the JSON data in a var and pass it to the function in expjs.js, as:
var data = data_from_ajax();
exp_js_function(data);
data_from_ajax() would receive JSON data from your controller and action method.
Please consider this as a starting point and not as a copy-paste solution

JQuery getJSON in MVC

I have the following JSon call that I want to call a method in Controller & accepts JSon object to update Partial View:
<script type="text/javascript">
function DoAjaxUpdate(btnClicked) {
btnClicked = $(btnClicked);
var $form = btnClicked.parents('form');
var url = '#Url.Action("Remove")';
$.getJSON(
url,
$form.serialize(),
function () {
if (data.htmlPartialView != null) {
return $("#divPartialView").load(obj.htmlPartialView);
}
});
return false;
}
</script>
Unfortunately, this isn't passing the data properly and instead appends it to the URL as a query string such as: http://www.myLink.com/MyController/Remove?dataID=1359&dataMember=1
Please help. Thanks
That's what happens with $("form").serialize(). It will serialize everything on the form and put it on the query string.
As long as your Remove action method takes an instance of the model that is on your original view, then it will be transformed using the values in the query string.
To send it as JSON, you'd have to use JSON.stringify():
JSON.stringify($form.serialize())
The callback need parameter,like this:
$.getJSON(
url,
$form.serialize(),
function (obj) {
if (obj.htmlPartialView) {
$("#divPartialView").load(obj.htmlPartialView);
}
});
by the way,if (obj.htmlPartialView) is same to if (data.htmlPartialView != null)
You are calling getJSON which sends the data as a GET request which uses the querystring. If you want to use the POST method, use (from the jQuery site):
$.post(url, data, function(data) {
});
or
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
More information: http://api.jquery.com/jQuery.post/

How to call a Webservice function from masterpage

I want to open a html page when user presses a function key.
Now the capturing of the function key works fine, but the logic to open the appropriate page is written in Code-Behind of master page.
I read on internet that if I want to call function in code behind then I have to create a web- service and call the webservice method from master page.
But for some reason this is not working.May be I am not calling the web service properly.
Can some body please help?
Many Thanks
<cc1:ToolkitScriptManager ID="ScriptManager1" runat="server" ScriptMode="Release" EnableHistory="true" EnableSecureHistoryState="false"
EnablePageMethods="true" CombineScripts="false">
<Scripts>
<asp:ScriptReference Path="~/ShowHelpPage.asmx" />
</Scripts>
</cc1:ToolkitScriptManager>
document.onkeydown = function(event){
if(window.event && window.event.keyCode == 113)
{
window.open("HelpFile/index.html");
}
else if(event.which == 113)
{
window.open("HelpFile/index.html");
DisplayHelpFile();
}
}
function DisplayHelpFile()
{
var i = PageMethods.DisplayHelpPage();// I think this is wrong
alert(i);
}
Web Method
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class ShowHelpPage : System.Web.Services.WebService
{
[WebMethod]
public string DisplayHelpPage()
{
return "Window.Html";
}
}
"I read on internet that if I want to call function in code behind
then I have to create a web- service and call the webservice method
from master page"
I assume in the context you are refering to methods and not functions. Do you want to call a method when you master page loads? I would think that you dont need to create a Web Service for this? Unless you want the client to initiate the request through Async and you are using JavaScript and AJAX to make the request. What are you trying to achieve? It seems to me this can be achieved through just javascript. If you call a page through JavaScript it should load itself?
Below achieving what you want but using just javascript.
function keyHandler(e)
{
... key handling script
if(myKey == 'F1')
{
window.location.href = '...';
}
}
document.onkeypress = keyHandler;
If you need to call this Web Service and it needs to be initiated from the Client you could use JQuery to do this. Use the same approach with ShowHelpPage.asmx storing the processing and your rendering handled through JavaScript. This also to the best of my knowledge removes the dependency on ToolkitScriptManager.
function DisplayHelpFile()
{
$.ajax({
type: "POST",
url: "ShowHelpPage.asmx/DisplayHelpPage",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success:function(result)
{
alert(result);
}
},
error: ErrorMessage
});
function ErrorMessage(result)
{
alert(result.status + ' ' + result.statusText + ' ' + result.responseText);
}
}
Your web method needs to be static.

Categories

Resources