I have followed the tutorial located here:
http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api
However, the main difference is I am using a 3rd party library to get a list of objects which I would like to return to the client.
Here is my index.html file:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Get Routes</title>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
</head>
<body>
<div>
<h2>All Routes</h2>
<ul id="routes" />
</div>
<script>
var uri = '../api/MH_Route_Selection';
$(document).ready(function () {
// Send an AJAX request
$.getJSON(uri)
.done(function (data) {
// On success, 'data' contains a list of products.
$.each(data, function (key, item) {
// Add a list item for the product.
$('<li>', { text: formatItem(item) }).appendTo($('#routes'));
});
});
});
</script>
</body>
</html>
My controller file:
namespace LMVeKanban.Controllers
{
public class MH_Route_SelectionController : ApiController
{
//GET ROUTES METHOD FOR URI: /api/MH_Route_Selection
[HttpGet]
public IHttpActionResult GetRouteList()
{
var routeManager = new LmvRouteManager(1);
List<Route> routes = routeManager.GetRoutes();
return Ok(Json(routes));
}
}
Everything works fine, the controller gets called and the return value routes, looks like: http://imageshack.com/a/img661/5648/ZQ59Rt.jpg
After the controller passes the list back, I get a 500 error from the server with no clue where it went wrong.
EDIT: Watching the Ok(routes) value shows that it has successfully converted the object:
EDIT 2: I have tried the following which also returns a 500 error in the same manner as the previous attempt
public HttpResponseMessage GetRouteList()
{
var routeManager = new LmvRouteManager(1);
List<Route> routes = routeManager.GetRoutes();
return Request.CreateResponse(HttpStatusCode.OK, routes);
}
Related
How to populate dropdownlist using WCF Rest Service:
First, this is my code to get service:
service.js
(function (app) {
app.service("GetCategoryService", function ($http) {
this.GetCategory = function () {
return $http.get("http://localhost:51458/ServiceRequest.svc/GetCategory/");
};
});
})(angular.module('entry'));
Entry.Ctrl
(function (app) {
'use strict';
app.controller('entryCtrl', entryCtrl);
entryCtrl.$inject = ['$scope'];
function entryCtrl($scope) {
$scope.pageClass = 'page-entry';
//To Get Category
$scope.Category = function () {
var promiseGet = GetCategoryService.GetCategory();
promiseGet.then(function (pl) { $scope.GetCategory = pl.data },
function (errorPl) {
console.log('Some Error in Getting Records.', errorPl);
});
}
}
})(angular.module('entry'));
This is entry.html
<div class="dropdown">
<select ng-model="Category" ng-options="item.ITEM_TEXT for item in Category"></select>
</div>
WCF Output JSON like:
[{"ITEM_TEXT":"INTERNAL APP"},{"ITEM_TEXT":"INTERNAL IT"}]
I don't know how to passing this to html, what I'm doing like this is not working. please help. thank
Make sure you have set ng-model different from the array name, also inject the service into your controller,
entryCtrl.$inject = ['$scope', 'GetCategoryService'];
DEMO
var app = angular.module('todoApp', []);
app.controller("dobController", ["$scope",
function($scope) {
$scope.Category = [{"ITEM_TEXT":"INTERNAL APP"},{"ITEM_TEXT":"INTERNAL IT"}];
}
]);
<!DOCTYPE html>
<html ng-app="todoApp">
<head>
<title>To Do List</title>
<link href="skeleton.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
<script src="MainViewController.js"></script>
</head>
<body ng-controller="dobController">
<select ng-model="selected" ng-init="selected = Category[0]" ng-options="item.ITEM_TEXT for item in Category"></select>
</body>
</html>
I am doing simple client request to check whether my server is working proper in my Android device or not. Below is my code. I am using HttpClient since it is a PCL project using Xamarin framework.
Android:
var client = new System.Net.Http.HttpClient(new HttpClientHandler());
client.BaseAddress = new Uri(App.BaseUrl);
var response = client.PostAsync(App.TestApi, new StringContent("")).Result;
if (response != null)
{
var responseString = response.Content;
string responseBody = responseString.ReadAsStringAsync().Result;
}
Server:
[HttpPost]
[Route("testapi/test")]
public HttpResponseMessage TestApi()
{
Log.WriteLog("testapi/test");
return Request.CreateResponse(HttpStatusCode.OK, "Success");
}
I am not posting any data. First I tried Get request in both server and client I got same HTML response, then I changed to POST, still same HTML response is coming instead of "Success"
When I try same request from RestClient, its returning "Success" as response. But in mobile instead of returning "Success" message, HTML string is returned as response. I have done many request like this, but this particular is behaving like this. This may be very simple, but I don't know how to search on this.
Response:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<!-- BEGIN PAGE SPINNER -->
<!-- BEGIN ACTUAL CONTENT -->
<!-- END ACTUAL CONTENT -->
<script>
</script>
</div>
<!-- END QUICK SIDEBAR -->
<script type="text/javascript">
</script>
<script></script>
<script type="text/javascript">
</script>
<script></script>
<script></script>
<script>
</script>
<script type="text/javascript">
</script>
<script>
jQuery(document).ready(function () {
});
</script>
</body>
</html>
One more thing what I have found is I have two servers, in one server I am getting "Success" response in device properly. But from another server I am not getting. Is it something to do with server setup?
Ey!
How I could refresh a Partial View with data out of the Model?
First time, when the page loads it's working properly, but not when I call it from the Action.
The structure I've created looks like:
Anywhere in my View:
#{ Html.RenderAction("UpdatePoints");}
My PartialView "UpdatePoints":
<h3>Your points are #ViewBag.points </h3>
At the Controller I have:
public ActionResult UpdatePoints()
{
ViewBag.points = _Repository.Points;
return PartialView("UpdatePoints");
}
Thanks for your help!
UPDATE
Thanks all for your help! Finally I used JQuery/AJAX as you suggested, passing the parameter using model.
So, in JS:
$('#divPoints').load('/Schedule/UpdatePoints', UpdatePointsAction);
var points= $('#newpoints').val();
$element.find('PointsDiv').html("You have" + points+ " points");
In Controller:
var model = _newPoints;
return PartialView(model);
In View
<div id="divPoints"></div>
#Html.Hidden("newpoints", Model)
So, say you have your View with PartialView, which have to be updated by button click:
<div class="target">
#{ Html.RenderAction("UpdatePoints");}
</div>
<input class="button" value="update" />
There are some ways to do it. For example you may use jQuery:
<script type="text/javascript">
$(function(){
$('.button').on("click", function(){
$.post('#Url.Action("PostActionToUpdatePoints", "Home")').always(function(){
$('.target').load('/Home/UpdatePoints');
})
});
});
</script>
PostActionToUpdatePoints is your Action with [HttpPost] attribute, which you use to update points
If you use logic in your action UpdatePoints() to update points, maybe you forgot to add [HttpPost] attribute to it:
[HttpPost]
public ActionResult UpdatePoints()
{
ViewBag.points = _Repository.Points;
return PartialView("UpdatePoints");
}
You can also try this.
$(document).ready(function () {
var url = "#(Html.Raw(Url.Action("ActionName", "ControllerName")))";
$("#PartialViewDivId").load(url);
setInterval(function () {
var url = "#(Html.Raw(Url.Action("ActionName", "ControllerName")))";
$("#PartialViewDivId").load(url);
}, 30000); //Refreshes every 30 seconds
$.ajaxSetup({ cache: false }); //Turn off caching
});
It makes an initial call to load the div, and then subsequent calls are on a 30 second interval.
In the controller section you can update the object and pass the object to the partial view.
public class ControllerName: Controller
{
public ActionResult ActionName()
{
.
. // code for update object
.
return PartialView("PartialViewName", updatedObject);
}
}
Thanks all for your help!
Finally I used JQuery/AJAX as you suggested, passing the parameter using model.
So, in JS:
$('#divPoints').load('/Schedule/UpdatePoints', UpdatePointsAction);
var points= $('#newpoints').val();
$element.find('PointsDiv').html("You have" + points+ " points");
In Controller:
var model = _newPoints;
return PartialView(model);
In View
<div id="divPoints"></div>
#Html.Hidden("newpoints", Model)
Controller :
public ActionResult Refresh(string ID)
{
DetailsViewModel vm = new DetailsViewModel(); // Model
vm.productDetails = _product.GetproductDetails(ID);
/* "productDetails " is a property in "DetailsViewModel"
"GetProductDetails" is a method in "Product" class
"_product" is an interface of "Product" class */
return PartialView("_Details", vm); // Details is a partial view
}
In yore index page you should to have refresh link :
Refresh
This Script should be also in your index page:
<script type="text/javascript">
$(function () {
$('a[id=refreshItem]:last').click(function (e) {
e.preventDefault();
var url = MVC.Url.action('Refresh', 'MyController', { itemId: '#(Model.itemProp.itemId )' }); // Refresh is an Action in controller, MyController is a controller name
$.ajax({
type: 'GET',
url: url,
cache: false,
success: function (grid) {
$('#tabItemDetails').html(grid);
clientBehaviors.applyPlugins($("#tabProductDetails")); // "tabProductDetails" is an id of div in your "Details partial view"
}
});
});
});
I am using a Jquery Token Input plugin. I have tried to fetch the data from the database instead of local data. My web service returns the json result is wrapped in xml:
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">[{"id":"24560","name":"emPOWERed-Admin"},{"id":"24561","name":"emPOWERed-HYD-Visitors"}]</string>
I have checked in the site http://loopj.com/jquery-tokeninput/ which says that the script should output JSON search results in the following format:
[
{"id":"856","name":"House"},
{"id":"1035","name":"Desperate Housewives"}
]
Both seems to be the same,but still i m not getting the items displayed in my page.
I am posting my code also.
My Js code: DisplayTokenInput.js
$(document).ready(function() {
$("#textboxid").tokenInput('PrivateSpace.asmx/GetDl_info', {
hintText: "Type in DL Name", theme: "facebook",
preventDuplicates: true,
searchDelay: 200
});
});
My web-service code:
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public string GetDl_info(string q)
{
string dl_input = string.Empty;
DataSet ds;
PSData ObjDl = new PSData();
ds = ObjDl.GetDistributionList(q);
List<DistributionList> DLObj = new List<DistributionList>();
foreach (DataRow datarow in ds.Tables[0].Rows)
{
DistributionList dl_list = new DistributionList();
dl_list.id = Convert.ToString(datarow["id"]);
dl_list.name = Convert.ToString(datarow["name"]);
DLObj.Add(dl_list);
}
dl_input = JsonConvert.SerializeObject(DLObj);
return dl_input;
}
}
public class DistributionList
{
public string id { get; set; }
public string name { get; set; }
}
I am posting the head portion of aspx code to show the library files i have included:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="../Styles/jquery-ui-1.8.20.custom.css" rel="stylesheet" type="text/css" />
<link href="../Styles/token-input.css" rel="stylesheet" type="text/css" />
<link href="../Styles/token-input-facebook.css" rel="stylesheet" type="text/css" />
<script src="Scripts/Lib/jquery-1.7.2.min.js" type="text/javascript"></script>
<script src="../Scripts/jquery.tokeninput.js" type="text/javascript"></script>--%>
<script src="DisplayTokenInput.js" type="text/javascript"></script>
<head>
You need to make sure that your request is a POST request. Not a get request. See this answer to find out more about why: How to let an ASMX file output JSON
I would assume that the code for the plugin isn't setting the content-type for ajax requests to JSON, so you could do it yourself before the service call with $.ajaxSetup ie:
$.ajaxSetup({
contentType: "application/json; charset=utf-8"
});
UPDATE: Apparently asmx services sometimes have issues with the 'charset=utf-8' portion, so if that doesn't work you could try just 'application/json'
UPDATE 2:
I don't think it's the contentType causing the issue, use the following to force a POST for ajax requests and see if this fixes it:
$.ajaxSetup({
type: "POST", contentType: "application/json; charset=utf-8"
});
UPDATE 3:
There is a default setting inside the plugin you're using that can change the requests from GET to POST. See here on it's GitHub repo: jquery.tokeninput.js
and in your copy of the js file in the project, change the line:
var DEFAULT_SETTINGS = {
// Search settings
method: "GET",
to
var DEFAULT_SETTINGS = {
// Search settings
method: "POST",
I also assume that the plugin constructs the query in a way that ignores the global jquery ajax settings anyway, so you shouldn't need to include my earlier snippets anymore.
In GridViewData.aspx.cs I have a method I want to call inside a javacsript function.
//This simple example method is from GridViewData.aspx.cs
private int ValidateNameUpdateable()
{
return 22;
}
I want to call this function from Javascript in default.aspx
<script type="text/javascript">
function validateForm()
{
if (ValidateNameUpdateable==22)
{
alert("Name is not updateable, the party already started.");
return false;
}
//if all is good let it update
UpdateInsertData()
}
</script>
Now hears the kicker, I am mostly using jqUery as UpdateInsertData() is a jquery Call and works fine. How do I use ValidateNameUpdateable to call jQuery to return the value from the c# method. . I believe this issue is with my jQuery Call as its just posting and I need to do a $.get or something?
function ValidateNameUpdateable()
{
$(document).ready(function ()
{
$.post("GridViewData.aspx")
});
}
Take a look at this question:
Using jQuery's getJSON method with an ASP.NET Web Form
It shows how to do it.
An example:
Default.aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
<!--
$(function () {
$.ajax({
type: "POST",
url: "WebService.asmx/ValidateNameUpdateable",
data: "{\"input\":5}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// (msg.d is the retrieved data)
var d = msg.d;
if (d == 22) {
alert("OK");
}
else {
alert("Not OK");
}
},
error: function (msg) {
}
});
});
//-->
</script>
</body>
</html>
WebService.cs (in App_Code):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
/// <summary>
/// Summary description for WebService
/// </summary>
[System.Web.Script.Services.ScriptService]
[WebService(Namespace = "http://tempuri.org/")] // <-- Put something like: services.yourdomain.com in here.
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class WebService : System.Web.Services.WebService {
[WebMethod]
public int ValidateNameUpdateable(int input)
{
return input == 5 ? 22 : -1;
}
}
WebService.asmx:
<%# WebService Language="C#" CodeBehind="~/App_Code/WebService.cs" Class="WebService" %>
I hope this explains the idea.
If you want to be able to pass more advanced structures (no int, or string) you might want to consider using JSON.
For the parsing of JSON I'll use the JQuery function parseJSON
All you need to do is create a structure on the web service (struct), and serialize it using the JSON serializer.
Another example using JSON:
Default.aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
<!--
$(function () {
function getRecord(id) {
$.ajax({
type: "POST",
url: "WebService.asmx/GetRecord",
data: "{\"id\":" + id + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// (msg.d is the retrieved data)
var d = $.parseJSON(msg.d);
if (d.RecordExists) {
alert("Record with id: " + d.ID + "\nFirstName: " + d.FirstName + "\nLastName: " + d.LastName);
}
else {
alert("Record doesn't exist.");
}
},
error: function (msg) {
}
});
}
getRecord(1);
getRecord(4);
getRecord(0);
});
//-->
</script>
</body>
</html>
WebService.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Serialization;
/// <summary>
/// Summary description for WebService
/// </summary>
[System.Web.Script.Services.ScriptService]
[WebService(Namespace = "http://tempuri.org/")] // <-- Put something like: services.yourdomain.com in here.
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class WebService : System.Web.Services.WebService {
[Serializable]
protected class Record
{
public bool RecordExists { get; set; }
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Record() // Initializes default values
{
RecordExists = true;
ID = 0;
FirstName = "";
LastName = "";
}
}
[WebMethod]
public string GetRecord(int id)
{
// Initialize the result
Record resultRecord = new Record();
resultRecord.RecordExists = true;
resultRecord.ID = id;
// Query database to get record...
switch (id)
{
case 0:
resultRecord.FirstName = "John";
resultRecord.LastName = "Something";
break;
case 1:
resultRecord.FirstName = "Foo";
resultRecord.LastName = "Foo2";
break;
default:
resultRecord.RecordExists = false;
break;
}
// Serialize the result here, and return it to JavaScript.
// The JavaScriptSerializer serializes to JSON.
return new JavaScriptSerializer().Serialize(resultRecord);
}
}
Please note that AJAX is Asynchronous, that means that even tough the pages are requested in a specific order, they are not received in a specific order. That means that even tough you request the records in order: 1, 4, 0, they can be received in any order, like 4, 1, 0, or 1, 0, 4.
I think you are looking for ajax. It lets you make asynchronous calls to a server and get the restult. You should make a simple aspx page that takes some request arguments and outputs the correct information. Then use ajax to call load that page and get the results.
here is a basic overview of ajax
http://www.prototypejs.org/learn/introduction-to-ajax
Here is the jQuery ajax call
http://api.jquery.com/jQuery.ajax/
Maybe your solution is to use load():
http://api.jquery.com/load/
You can't do it directly, you need to post your data through an httphandler (ashx), for example. Then your handler returns a json object. You delve into to find the response you want.
ASP.NET - Passing JSON from jQuery to ASHX
[]'s