Reputation: 185
I try to use the Kendo UI Autocomplete tool with a C# datasource. It seems very easy in PHP:
<?php
include("connection.php");
$arr = array();
$stmt = $db->prepare("SELECT StateID, StateName FROM USStates WHERE StateName LIKE ?");
// get the StartsWith value and append a % wildcard on the end
if ($stmt->execute(array($_GET["StartsWith"]. "%"))) {
while ($row = $stmt->fetch()) {
$arr[] = $row;
}
}
// add the header line to specify that the content type is JSON
header("Content-type: application/json");
echo "{\"data\":" .json_encode($arr). "}";
?>
But I want to use a CSHtml file or something equivalent, do you have any idea on how to accomplish this?
I don't want to create a controller attached with a model, etc... If it's possible to make it with only one page, it would be great.
Upvotes: 0
Views: 517
Reputation: 6876
If you are using MVC Create a controller like so....
public class DataController : Controller
{
public JsonResult GetStates()
{
var data = GetData();
return Json(new
{
data = data.Select(r => new
{
StateId = r.ID,
StateName = r.Name
})
});
}
}
Then all you have to do is set the datasource url to /data/GetStates
If you are using webforms I would create a generic handler or a webservice (depending on how many functions you need)
public class LoadStates : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
JavaScriptSerializer json = new JavaScriptSerializer();
var data = GetData();
context.Response.ContentType = "application/json";
context.Response.Write(json.Serialize(new
{
data = data.Select(r => new
{
StateId = r.ID,
StateName = r.Name
})
}));
}
public bool IsReusable
{
get
{
return false;
}
}
}
For completness sake.. here is how you would pull off the same using a ashx webservice
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod, ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string HelloWorld()
{
var data = GetData();
return new
{
data = data.Select(r => new
{
StateId = r.ID,
StateName = r.Name
})
};
}
}
Upvotes: 2