I have Kendo TreeView in which I can Call an Ajax method and hit my MVC controller method
However, my understanding was that
update: "should" be called with datasource.sync() ( homogeneous = my datasource )
$("#syncCall").click(function(e) {
console.log('before sync');
homogeneous.sync();
});
This DOES show before sync in chrome dev console ....
However, my mvc controller method SyncAllNodes breakpoint is NEVER hit.
Here is the HierarchicalDataSource
var homogeneous = new kendo.data.HierarchicalDataSource({
transport: {
read: {
url: serviceRoot + "/GetReportGroupAssignments",
dataType: "json"
},
update: {
url: "/Report/SyncAllNodes",
dataType: "json"
}
},
schema: {
model: {
id: "Id" //"ReportGroupName"
,
hasChildren: "Id"
}
}
});
Joseph,
Not sure if this has anything to do with it, but your Update url looks different than your Read url. Namely, the "serviceRoot +" part. Can you verify that the Update url points to the correct location?
Are you getting any javascript errors after the console.log(...) call?
Also, confirm that you have changes to save. If there are no changes, the sync method will not do anything.
Regards,
Related
i have bind drop down using WebMethod (Services)
I have multiple drop down list and need to bind on mutully dependent to each other like cascading of dropdown list but while passing value for one selected vale its showing null while debugging on my web method
WebMethod:
public static List<Company> GetCompanies(string CountryCode, string CompanyCode)
{
GetInitiatorList.MasterDataServiceClient oClient = new GetInitiatorList.MasterDataServiceClient();
Almarai.GiveAway.GetInitiatorList.ALM_COMPANY_M[] initiatorsList = oClient.GetActiveCompanies(CountryCode, CompanyCode) List<Company> Companyes = new List<Company>();
foreach (Almarai.GiveAway.GetInitiatorList.ALM_COMPANY_M company in initiatorsList)
{
Companyes.Add(new Company()
{
CountryCode = company.CompanyCode,
CompanyName = company.CompanyName
});
}
return Companyes;
}
JQuery
$('#ddlCountry').change(function (e) {
var selectedCountry = $('#ddlCountry').val();
$.ajax({
type: "POST",
url: "Header.aspx/GetCompanies",
data: JSON.stringify({ CountryCode: selectedCountry, CompanyCode: 'SAU' }),
dataType: "json",
contentType: "application/json",
success: function (res) {
$.each(res.d, function (data, value) {
$("#ddlCompany").append($("<option></option>").val(value.CompanyId).html(value.CompanyName));
$('#ddlCompany').change(function (e) {
Aspx:
<div class="col-md-8">
<select id="ddlCountry">
<option value="0">--Select Country--</option>
</select>
</div>
Where i am doing wrong Please guide me
To get the currently selected value from dropdown:
$('#ddlCountry').val();
To get the currently selected text from dropdown:
$('#ddlCountry :selected').text();
You can check first your ajax call is working properly or not , by sending hard coded text by specifying like this in ajax call:
$.ajax({
type: "POST",
url: "Header.aspx/GetCompanies",
data: JSON.stringify({ CountryCode: 'USA', CompanyCode: 'SAU' })
....
Then you can check are you assign dropdown values properly or not ? If you only want text not value then you can use as I have mentioned on top. I think it will solve your problem. Please let me know if it isn't.
============ Updated (after reading comments) ======================
I have created a sample demo based on your sample. As I don't have the service code as you have so it is very simple to give it a test to check either it is working or not or it will give me the same error as like yours.
What I have done for testing this may be look trivial to you but please check , it works for me and give me right result. here is screen shot of Route Config file , take a look at the red circle ( I have to change this for web method works)
Screen shot of chrome dev tools ( for Contact.aspx page here for simplicity)
And finally Contact.aspx -> GetCompanies web method break point hit screen shot , here i have modified method body for simplicity , just to check data binding is working or not.
So , it's work for me. Would you please check all of your step one by one and let me know. If it will help you then it will be my pleasure.
I think you don't need to stringify it.
Instead of:
data: JSON.stringify({ CountryCode: selectedCountry, CompanyCode: 'SAU' }),
try:
data: { CountryCode: selectedCountry, CompanyCode: 'SAU' },
Very silly point I miss out here From web Method I Was returning CompanyCode as you can see
CountryCode = company.CompanyCode,
CompanyName = company.CompanyName
And In Html I was trying to bind CompanyId as you can see here :
$("#ddlCompany").append($("<option></option>").val(value.CompanyId).html(value.CompanyName));
So it was coming null or 0 for obvious region.
I Just replace value.CompanyId to CompanyCode and its now working perfectly
Do you need .aspx suffix?
Try like this url: "Header/GetCompanies",
I've a Web app with a button that makes a call to an API to refresh data:
[AcceptVerbs("GET")]
[Route("refreshFromService/{guid}")]
public HttpResponseMessage RefreshDataFromService(string guid)
{
if (!string.IsNullOrEmpty(guid) && guid.Length == 36 && new Guid(guid) == new Guid("C943F8E4-647D-4044-B19E-4D97FA38EDE0"))
{
new AdData().RefreshCacheAdData(true);
new JdeData().RefreshCacheJdeData(true);
return new HttpResponseMessage(HttpStatusCode.OK);
}
return new HttpResponseMessage(HttpStatusCode.Forbidden);
}
Actually, it's an AJAX call, so in my Network Tab in Google Chrome, I see the request is in pending for 5 minutes.
How can I make this method an async method and how can I refresh my UI to show progress?
EDIT
When I refresh the page, I want the Progress Status to be updated.
First of all, it has nothing to do with a backend. So solution to your problem lies on frontend site. Ajax are asynchronous by nature so you can do something like that.
const loader = document.createElement('span')
// some styles for the loader
// i'm using body just for example purposes
document.body.appendChild(loader)
fetch('refreshFromService/{guid}')
.then(data => {
document.body.removeChild(loader)
// do something with data
return data
})
You have to handle it on UI like this:
function getFlag() {
var option = {
url: '/controllerName/actionName',
data: JSON.stringify({}),
method: 'post',
dataType: 'json',
contentType: 'application/json;charset=utf-8'
};
$.ajax(option).success(function (data) {
$("#picture").append("<img id=\"img1\" src=" + data.img_path + "\ />");
});
};
I am using this code in UI for getting flags at runtime. So you need to write same type of code and get response from the backend.
url: '/controllerName/actionName' is the controller in MVC and then action implemented in that controller.
Request this method in UI with document.ready
I hope I have made sense to you. If still not clear write back i will explain further.
Cheers!
I have the following jQuery call in the razor view.
$.getJSON('/Controller/ActionName/'+ #ViewContext.RouteData.Values["Name"] + '?Date=' + ('#StartDate').val(), function (data) {
alert(data);
});
The error in chrome browser console is that the below URL has returned no page found.
http://localhost:{portNumber}/Controller/ActionName/John?Date=9/21/2014&_=1413867422739
it is true because of the added extra token to the end of the url.
Can any one please let me know the reasons for the extra token?
I have an appropriate method in the controller and not able to figure out a solution.
The routeConfig.cs file is not changed and it has the default values to it.
Please let me know in comments if you need further information. I am not able to understand which information to furnish.
Route information:
{
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", name = UrlParameter.Optional }
);
}
Action Signature in the controller
public JsonResult ActionName(string**?** name, DateTime startDate)
{
var model = new ViewModel();
model.loadItems(name**.value**, startDate);
return Json(model.Data, **JsonRequestBehavior.AllowGet**);
}
Answer:
Made the above changes in surrounded by ** and the code worked.
Thank you for the comments and answers.
Update:
I have mentioned the default values in order to hide the unrequired information.
localhost is correct and other pages are working fine just a small part of ui which is related to this ajax call is not working.
No controller is name something else.
Can you please provide a solution for sending date values in URLS?
Change you call to (assuming your controller is really named ControllerController
$.getJSON('/Controller/ActionName/', { name: #ViewContext.RouteData.Values["Name"], startDate: $('#StartDate').val(), function (data) {..
You have a few problems here. Your default route accepts a parameter named ID but your method only has parameters name and startDate. You are not passing any parameters with those names (you are passing one for date but that does not match the method signature parameter)
Note you should not hard code the controller and action names this way. The recommend ways is
var url = '#Url.Action("ActionName", "Controller")';
var StartDate= ('#StartDate').val();
var url="/Controller/ActionName/'+ #ViewContext.RouteData.Values["Name"] + '/";
$.ajax({
url: url,
data: { Date: StartDate},
cache: false,
type: "POST",
success: function (data){
},
error: function (data){
}
});
I'm using a Kendo grid to display results from a webservice. The webservice is accessed in a controller and then we point the Kendo grid dataSource to the controller like so:
JavaScript
var servicePath = "/Home/Search";
var postData = { "searchTerm" : searchTerm, "targetDB" : targetDB }
var grid = $("#grid1").kendoGrid({
pageable: {
pageSize: 10
},
dataSource: {
error: function (e) {
if (e.errors !== false) {
$("#errorContainer").html(e.errors);
}
},
transport: {
read: {
url: servicePath,
dataType: "json",
data: postData,
type: "POST"
}
},
},
dataBound: function (e) {
//Do Stuff
}
});
Controller
[HttpPost]
public ActionResult Search(string searchTerm, string targetDB)
{
//Do Search and Return JSON
}
Problem
This works wonderfully when my URL is http://localhost/Home/Index but fails whenever it's something else, such as http://localhost/ (default when project is run from root). I've experienced the same problems using a jQuery .ajax call as the kendo grid service call.
Question
So my question is, how can I put in the correct service URL for the Kendo Grid (or in general when pointing to a controller) and know it will work in all path variations?
I've tried using variations of location.host to get the full URL regardless then append the controller and method, but the Kendo service call fails with no error.
I imagine I should be able to parse the url and use what I need, but I've found that when I am at the root of the webpage I can't figure out what to put to make an ajax call work. I've tried using the controller/method and the entire url? I've also tried various techniques described below.
What am I missing? Is there a convention or technique I could use instead?
Edit
I also tried putting a hidden field on the page with a value of the controller URL:
<input type="hidden" value="#Url.Action("Search", "Home"); " id="serviceURL" />
And then using that value in the JS:
var servicePath = $("#serviceURL").val();
But I found that the value of #Url.Action() (Value : Home/Search) is the same whether your url is http://localhost/ or http:localhost/Home/Index, so no luck. This still does not work when you're on the root page where the url looks something like "localhost/".
Thanks!
I am making an ASP.net MVC application And I would like it so when a user clicks on a link it performs an ajax call sending data to the controller and then returning other data back to the view.
This is the method I would like to call in my controller:
public JsonResult GetImage(string url)
{
Image image = Image.FromFile(url, true);
byte[] byteImage = converter.ImageToBytes(image);
return Json(new { byteImage }, JsonRequestBehavior.AllowGet);
}
And here is the controllers location:
08983ClassLibrary\EpostASP\Controllers\CustomerController.cs
This is my Ajax Call:
$.ajax({
url: "~/Controllers/CustomerController/GetImage/",
type: 'POST',
contentType: 'application/json',
data: "url="+url,
success: function (image) {
document.getElementById("image").src = "data:image/png;base64," + image;
showImage();
}
});
When i place my breakpoints in the code I can see it hitting the ajax call then stepping over it never reaches the controller and doesnt give any errors.
Any ideas?
The main issue is here -
url: "~/Controllers/CustomerController/GetImage/",
You see, ~ is a server side literal, in other words, when you use this in a ASP.net server side path, it is replaced by the current server application folder location. This was the traditional ASP.Net way. This line has 2 errors -
This url will never work. Because its inside a string in JS and thus ASP.net does not know that it has to replace it with server path. Now comes the second error, even if ASP.net could detect and convert it, it will still not work. Because of the point I described at 2 -
Since you are using ASP.net MVC, it's not a good practice. The more conventional MVC way is to create routes and use those routes. Because in ASP.net you have the option to link to a page (.aspx, .ascx) directly. But MVC controller actions cannot be linked like that. So you have to create routes in your route config (check Global.asax) and then use that route as the url in here. BY default MVC apps will support the following format -
<host>/{controller}/action
example -
'localhost/Home/Index`
Notice that I didn't write HomeController, because by default controllers are supposed to ignore the trailing string Controller.
I hope this helped and just incase you are looking for a solution for your current situation try this (I haven't tested but it should be like this) -
$.ajax({
url: "Customer/GetImage",
type: 'POST',
contentType: 'application/json',
data: "url="+url,
success: function (image) {
document.getElementById("image").src = "data:image/png;base64," + image;
showImage();
}
});
but to be on the safe side, make sure you use -
[HttpPost]
public JsonResult GetImage(string url)
{
}
UPDATE:
the maproute (as requested in comment ) will work with any of these routes. But can also work with different routes config. Route config is very very flexible, it is just a matter to setup the routes the way it works for you. -
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute(
"...", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
routes.MapRoute(
"...", // Route name
"{controller}/{action}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
routes.MapRoute(
"...", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Customer", action = "GetImage", id = "" } // Parameter defaults
);
routes.MapRoute(
"...", // Route name
"Customer/GetImage/{id}", // URL with parameters
new { controller = "Customer", action = "GetImage", id = "" } // Parameter defaults
);
..... //all of these mentioned route will land on the same url
}
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
}
Your ajax script says it is looking for a POST action method.
$.ajax({type: 'POST',
Have you decorated the action method with POST?
[HttpPost]
public JsonResult GetImage(string url)
{
}
Also, adjust your ajax data parameter
$.ajax({
data: {
"url": url
},
If you are using chrome you can go the developer tools -> network tab and see all the server requests being made. Hit your button and you will see it pop up and show you the response codes, headers etc. In your case it will be red and will tell you what went wrong
If you are using web api... Your method is starting with "Get" GetImages so you need to decorate the method with [HttpPost]
I have found that using fiddler is the best way to see what is going on in MVC.
Start up fiddler, run the code again and see what actually came back. Most likely (as mentioned by Yorro) is that you got a 404 error and as you have no error handling in your json call, you wont ever see the error.
$.ajax({
url: '#Url.Action("GetImage", "Customer")',
type: 'POST',
contentType: "application/json; charset=utf-8",
data: "url="+url,
success: function (image) {
document.getElementById("image").src = "data:image/png;base64," + image;
showImage();
}
});
If using IE, and your controller is hitting the first time only add ...
$.ajax({
cache:false,
...
Some time it will work or some time not work so don't mention URL such as static "~/Controllers/CustomerController/GetImage/" please follow the dynamic way
So you will change the code snippet such as below
$.ajax({
url: "#Url.Action("GetImage", "CustomerController")",
type: 'POST',
contentType: 'application/json',
data: "url="+url,
success: function (image) {
document.getElementById("image").src = "data:image/png;base64," + image;
showImage();
}
});
hopefully this code will be resolved your problem !!