Kendo UI TreeListDataSource Read() only works when running locally - c#

I have a Kendo TreeList with its datasource defined as
var ds = new kendo.data.TreeListDataSource({
transport: {
read: {
url: "/Home/Read/",
type: "POST",
dataType: "json"
}},
schema:...
}
My controller's read method is:
[HttpPost]
public string Read()
{
log.Info("Start read()");
var vm = vmHelper.GetClientOrgListViewModel();
var json = new JavaScriptSerializer().Serialize(vm.FacilityList);
log.DebugFormat("json read returned: {0}", json);
return json;
}
Everything works great as long as I run locally through VS but once I deploy to our staging server, the Read() transport code never gets executed. I get a 500 error. Pressing F-12 to view the requests in IE shows a 500 error
Any ideas or suggestions on why it works locally but not on the server and how to resolve this issue?

Try building your URL using #Url.Action("Read", "Home")
var ds = new kendo.data.TreeListDataSource({
transport: {
read: {
url: '#Url.Action("Read", "Home")',
type: "POST",
dataType: "json"
}},
schema:...
}
If your javascript code is in a javascript file you won't be able to use the razor helpers. What I do in that case is add it to a list of URL's I keep in my layout file. Like this:
<script type="text/javascript">
var Configuration;
(function (Configuration) {
var urls = {
Read: '#Url.Action("Read", "Home")'
}
Configuration.url = urls;
})(Configuration || (Configuration = {}));
</script>
Then just use it as:
transport: {
read: {
url: Configuration.url.Read
}
}

Related

How to call api from ASP.NET razor view

Just as stated above, I am not sure how to call an API.
I have done it using fetch in the example below:
fetch("https://localhost:5001/api/patients/add", {
method: "POST",
mode: "cors",
cache: "no-cache",
headers: { "Content-Type": "application/json" },
body: postBody
});}
But it seems there is a different way of doing things in Razor view.
Below is what I have in my API:
// GET: api/Patients/5
[HttpGet("{id}")]
public async Task<ActionResult<Patient>> GetPatient(int id)
{
var patient = await _context.Patient.FindAsync(id);
if (patient == null)
{
return NotFound();
}
return patient;
}
It's just the GET made when creating an API in Visual Studio.
The following ajax call, within a script tag inside the razor page - although this is not best practice - would work as follows:
$.ajax({
type: "GET",
url: "#Url.Action("GetPatient", "Patients")",
data: { id : 1234 },
success: function(result){
//do something with result here
alert(result);
}
});
The second parameter of Url.Action is the Controller Name. This may need to be adapted for yourself.
This is what I ended up doing that worked. Thanks for the help guys!
$(document).ready(function () {
var options = {};
options.url = "https://localhost:44381/api/States";
options.type = "GET";
options.dataType = "json";
options.success = function (states) {
states.forEach(function (state) {
$("#state").append("<option>" + state.stateName + "</option>"
)
});
};
options.error = function () {
$("#msg").html("Error while calling the Web API!");
};
$.ajax(options);
});

Posting AJAX string to MVC Controller

I am trying to post a string (the name of the href the user clicked on) using AJAX to my MVC controller (which it will then use to filter my table results according to the string).
Whilst I have managed to get it to post (at-least according to the alerts) on the AJAX side, it doesn't seem to arrive properly on the controller side and is seen as null in my quick error capture (the if statement).
Please excuse the useless naming conventions for the moment. I've been going through countless methods to try and fix this, so will name properly when I've got a proper solution :).
I've been at work for this for a long while now and can't seem to solve the conundrum so any help is appreciated please! I'm very new to AJAX and MVC in general so I'm hoping it's a minor mistake. :) (FYI I have tried both post and get and both seem to yield the same result?)
Controller:
[Authorize]
[HttpGet]
public ActionResult GetSafeItems(string yarp)
{
using (CBREntities2 dc = new CBREntities2())
{
if (yarp == null)
{
ViewBag.safeselected = yarp;
}
var safeItem = dc.Items.Where(a => a.Safe_ID == yarp).Select(s => new {
Serial_Number = s.Serial_Number,
Safe_ID = s.Safe_ID,
Date_of_Entry = s.Date_of_Entry,
Title_subject = s.Title_subject,
Document_Type = s.Document_Type,
Sender_of_Originator = s.Sender_of_Originator,
Reference_Number = s.Reference_Number,
Protective_Marking = s.Protective_Marking,
Number_recieved_produced = s.Number_recieved_produced,
copy_number = s.copy_number,
Status = s.Status,
Same_day_Loan = s.Same_day_Loan
}).ToList();
// var safeItems = dc.Items.Where(a => a.Safe_ID).Select(s => new { Safe_ID = s.Safe_ID, Department_ID = s.Department_ID, User_ID = s.User_ID }).ToList();
return Json(new { data = safeItem }, JsonRequestBehavior.AllowGet);
}
}
AJAX function (on View page):
$('.tablecontainer').on('click', 'a.safeLink', function (e) {
e.preventDefault();
var yarp = $(this).attr('safesel');
var selectedSafeZZ = JSON.stringify("SEC-1000");
$.ajax({
url: '/Home/GetSafeItems',
data: { 'yarp': JSON.stringify(yarp) },
type: "GET",
success: function (data) {
alert(yarp);
console.log("We WIN " + data)
},
error: function (xhr) {
alert("Boohooo");
}
});
})
** The Alert reveals the correct type: "SEC-1000"
But the console Log shows: WE WIN [Object object]??
I have tried something basic in a new mvc dummy project :
View page basic textbox and a button :
<input type="text" id="txt_test" value="test"/>
<button type="button" class="btn" onclick="test()">Test</button>
<script type="text/javascript">
function test()
{
var text = $("#txt_test")[0].value;
$.ajax({
url: '#Url.RouteUrl(new{ action="GetSafeItems", controller="Home"})',
// edit
// data: {yarp: JSON.stringify(text)},
data: {yarp: text},
type: 'GET',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function(data) {
// edit
// alert(JSON.stringify(data));
alert(data.data);
}});
}
</script>
Controller :
[HttpGet]
public ActionResult GetSafeItems(string yarp)
{
return Json(new {data = string.Format("Back end return : {0}",yarp)}
, JsonRequestBehavior.AllowGet);
}
Alert result => {"data":"Back end return : \"test\""}
It's a simple ajax call to a web method. You don't return a view, so I don't understand the use of
if (yarp == null)
{
ViewBag.safeselected = yarp;
}
Also I see an [Authorize] attribute, you perhaps use some authentication and I don't see any authentication header on your ajax call
Try this:
$.each(data, function (i) { console.log("We WIN " + data[i].Serial_Number )});

ajax request to razor page using handler

I am trying to get data from Active.cshtml.cs file using ajax call.
Here is the jquery code:
var turl = '/Active?handler=Clients/' + id;
$.ajax({
type: "GET",
url: turl,
dataType: "json",
success: function (result) {
alert(JSON.stringify(result));
});
Here is Active.cshtml.cs method
public JsonResult OnGetClients()
{
return new JsonResult("new result");
}
The status is 200 Ok, but it shows the entire webpage in response. Ideally it should return "new result" in Network tab of developer tools. Is it that I have Active.cshtml and Active.cshtml.cs in Pages that creates the confusion? How can I resolve it?
Thanks
For razor pages, you should be passing the parameter value(s) for your handler method in querystring.
This should work.
yourSiteBaseUrl/Index?handler=Clients&53
Assuming your OnGetClients has an id parameter.
public JsonResult OnGetClients(int id)
{
return new JsonResult("new result:"+id);
}
So your ajax code should look something like this
var id = 53;
var turl = '/Index?handler=Clients&id=' + id;
$.ajax({
type: "GET",
url: turl,
success: function (result) {
console.log(result);
}
});

jQuery AJAX source is an ASP.NET function on the same page (Default.cshtml). How do I send/receive?

We're migrating to ASP.NET from PHP, and I'm a little new to jQuery. So, I'm having a little bit of an issue with this function:
[System.Web.Services.WebMethod]
internal static string[] GetSearchSuggestions(string SearchQuery)
{
string ConnectionString = "Data Source=<omitted>;Initial Catalog=<omitted>;Integrated Security=True";
string TSQL_Query = String.Format("SELECT DISTINCT TOP 5 [colum-name] from [table] WHERE [column-name] LIKE '{0}%' AND len([column-name]) > 0", SearchQuery);
List<string> SearchSuggestions = new List<string>();
using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(ConnectionString))
{
using (System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand(TSQL_Query, connection))
{
connection.Open();
System.Data.SqlClient.SqlDataReader r = command.ExecuteReader();
while (r.Read())
{
SearchSuggestions.Add(r.GetString(0));
}
}
}
return SearchSuggestions.ToArray();
}
And this is my jquery:
<script type="text/javascript">
$(document).ready(function () {
$("#SearchQueryBox").autocomplete({
source: function (request, response)
{
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: GetSearchSuggestions,
data: "{'term':'" + $("#SearchQueryBox").val() + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("error");
}
});
}
});
});
</script>
Now, if I were to turn this into a simple post that loads the next page, the above ASP.NET C# code works. However, I can't seem to get a jQuery response under any of my test circumstances.
This page is called Default.cshtml, and is using the ASP.NET Razor syntax. The function is located on the same page like this:
#functions
{
// GetSearchSuggestions() code here
}
How do I appropriately post to an ASP.NET function on the same page, and receive a response?
Thanks in advance!
I am assuming you are using ASP.NET MVC. If that's the case:
You would need to move your function (that is in Default.cshtml) to a new ActionMethod with HttpPost in your Controller.
So, let's say your Default.cshtml is loaded by HomeController.cs. In HomeController.cs, you would create new ActionMethod:
[HttpPost]
public void ActionResult GetSearchSuggestions() {
// GetSearchSuggestions() code here
}
Also, in your jQuery, the option url of .ajax will need to be the URL of your site. Again, with the example I gave above, the URL would be http://www.example.com/Home/GetSearchSuggestions
You can't call C# or ASP.NET function from jQuery like that, you must specify the URL of that ActionMethod.
UPDATE
On the second look, I am not sure if where your internal static string[] GetSearchSuggestions(string SearchQuery) located. But you can move that to HomeController.cs I was talking about. Just remove the [System.Web.Services.WebMethod] and changed to [HttpPost]

JQuery values passed to WebApi is always null

I am having trouble with Web Api and was hoping someone here might be able to help me.
I have a jQuery method as follows ...
function OnInsert(evt) {
var truckId = $("#txtTruckId").val();
var truckReg = $("#txtTruckReg").val();
var description = $("#txtDescription").val();
var condition = $("#txtCondition").val();
var data = '{"obj":{"TruckId":"' + truckId + '","Reg":"' + truckReg +
'","Description":"' + description + '","Condition":"' + condition + '"}}';
var json = JSON.stringify(data)
$.ajax({
url: '/api/Values',
cache: false,
type: 'POST',
data: json,
dataType: 'json',
success: function (results) {
$("#txtTruckId").val('');
$("#txtTruckReg").val('');
$("#txtDescription").val('');
$("#txtCondition").val('');
$.getJSON("api/Values", LoadCustomers);
alert('Truck Added !');
}
})
}
When I debug that the 'data' variable successfully captures the data.
I then have a function in my WebApi controller ...
// POST api/values
public void Post(TruckInfo obj)
{
WebApiTestEntities db = new WebApiTestEntities();
db.TruckInfoes.Add(obj);
db.SaveChanges();
}
However, when I debug thst all of the parameters are showing a null value.
I found this:
http://kennytordeur.blogspot.co.uk/2012/12/web-api-passing-complex-type-in-json.html
Which states I need the following line of code in the Global.asax but that hasn't worked.
ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());
I also found this which kind of comes up with an answer but after trying to alter my code so it looks like the code they have written it still doesn't work.
jQuery posts null instead of JSON to ASP.NET Web API
Is any one able to help?
Thanks in advance
Lex
Start by fixing your JSON:
var data = {
truckId: truckId,
reg: truckReg,
description: description,
condition: condition
};
var json = JSON.stringify(data);
and then make sure you specify the correct content type request header:
$.ajax({
url: '/api/Values',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: json,
success: function (results) {
$("#txtTruckId").val('');
$("#txtTruckReg").val('');
$("#txtDescription").val('');
$("#txtCondition").val('');
$.getJSON("api/Values", LoadCustomers);
alert('Truck Added !');
}
});
I found this:
http://kennytordeur.blogspot.co.uk/2012/12/web-api-passing-complex-type-in-json.html
Which states I need the following line of code in the Global.asax but
that hasn't worked.
No, no, no. Not necessary as long as you format properly your JSON request, the Web API will bind it to your model.

Categories