AJAX path is not right - c#

I have a web application with a few cascading dropdown lists. So I use ajax to update the value of the next dropdown list. I put the javascript script in a separate file.
// Code that triggers when there is a change in Activity drop down.
$('#ActivityId').change(function () {
var activityId = $(this).val();
// Empty the Workstation.
$('#WorkstationId').empty();
$('.showhide-workstation').show();
var url = "~/WorkOrderSubmissions/GetWorkstationsByActivityJson";
// AJAX call that re-populate Workstation drop down depending on the Activity selected.
$.ajax({
type: 'POST',
url: url,
dataType: 'json',
data: { activityId: activityId },
success: function (codes) {
$('#WorkstationId').append('<option value=""></option>');
$.each(codes, function (i) {
$('#WorkstationId').append('<option value = "' + codes[i].Value + '">' + codes[i].Text + '</option>');
});
},
error: function (ex) {
$('#WorkstationId').append('<option value=""></option>');
}
}); // END $.ajax() on GetRejectCodesByActivityJson
}); // END $('#ActivityId').change()
The code works when I run it from inside Visual Studio. It does not work when I deploy it to my local web server. I deploy it to
http://localhost/mea
When I open Developer Tools in Chrome, I see the error.
POST http://localhost/~/WorkOrderSubmissions/GetLinesByWorkorderJson 404 (Not Found)
I tried to to change the url to
url = ~/WorkOrderSubmissions/GetLinesByWorkorderJson
url = /WorkOrderSubmissions/GetLinesByWorkorderJson
url = WorkOrderSubmissions/GetLinesByWorkorderJson
None of them work. I thought ~ is supposed to go to the root of the web application, which is http://localhost/mea.

The ~ syntax is only recognised by ASP.Net; it will be taken literally by any JS code. You need to provide the URL via your C# code to JS:
var url = '#Url.Content("~/WorkOrderSubmissions/GetWorkstationsByActivityJson")';
Or better yet:
var url = '#Url.Action("GetWorkstationsByActivityJson", "WorkOrderSubmissions")';

Related

Export iCal from database

I'm trying to figure out how to be able to export an iCal file from my calendar. I can't get it to work, it does not start to "download" the file.
Right now I just try to get one meeting, but later on I will make a for loop to get all the meetings in the database to the iCal file, but I just want to check if it works, but it does not.
This below is my method in the controller and later the jQuery to call the method.
[HttpPost]
public ActionResult AddToICalendar()
{
var ctx = new OruBloggenDbContext();
var meetings = ctx.Meetings.FirstOrDefault(u => u.MeetingID == 1);
var icalStringbuilder = new StringBuilder();
icalStringbuilder.AppendLine("BEGIN:VCALENDAR");
icalStringbuilder.AppendLine("PRODID:-//MyTestProject//EN");
icalStringbuilder.AppendLine("VERSION:2.0");
icalStringbuilder.AppendLine("BEGIN:VEVENT");
icalStringbuilder.AppendLine("SUMMARY;LANGUAGE=en-us:" + meetings.MeetingTitle);
icalStringbuilder.AppendLine("CLASS:PUBLIC");
icalStringbuilder.AppendLine(string.Format("CREATED:{0:yyyyMMddTHHmmssZ}", DateTime.UtcNow));
icalStringbuilder.AppendLine("DESCRIPTION:" + meetings.MeetingDesc);
icalStringbuilder.AppendLine(string.Format("DTSTART:{0:yyyyMMddTHHmmssZ}", meetings.MeetingStartDate));
icalStringbuilder.AppendLine(string.Format("DTEND:{0:yyyyMMddTHHmmssZ}", meetings.MeetingEndDate));
icalStringbuilder.AppendLine("SEQUENCE:0");
icalStringbuilder.AppendLine("UID:" + Guid.NewGuid());
icalStringbuilder.AppendLine("END:VEVENT");
icalStringbuilder.AppendLine("END:VCALENDAR");
var bytes = Encoding.UTF8.GetBytes(icalStringbuilder.ToString());
return this.File(bytes, "text/calendar", "ical.ics");
}
Javascript:
<script>
$(function () {
$(document)
.on("click", "#icalBtn", function () {
exportiCal();
});
function exportiCal() {
$.ajax({
url: '/MeetingCalendar/AddToICalendar',
type: "POST",
//data: { downloadFileName = "thisEvent.ics" },
success: function (data) {
alert("hejejje");
}
});
}
});
</script>
The reason nothing downloads is because you can't download files via AJAX. Instead of being delivered to a file on your computer's disk, the downloaded content is going into the data variable in your "success" function.
To solve it, instead of using AJAX, make your action method accept GET requests and just user a regular hyperlink to link the user to it:
[HttpGet]
public ActionResult AddToICalendar()
{
//..etc
and
Download to iCalendar
You can remove all your jQuery code.
N.B. Logging that data value to the console (instead of just alerting meaningless junk) - or using your browser's network tools to see what is going on - would have let you see that, and you might have seen the problem sooner...maybe you need to do a bit more debugging in future.

Server result to webpage

I am trying to simply write out some data to my webpage as a result of a callback. Everything works up until the point where I need to output the result of the callback.
Client-side:
function toServer(data) {
var dataPackage = data + "~";
jQuery('form').each(function () {
document.getElementById('payload').value = JSON.stringify({ sendData: dataPackage });
$.ajax({
type: "POST",
async: true,
url: window.location.href.toString(),
data: jQuery(this).serialize(),
success: function (result) {
//this does not work because it just puts an entire source code copy of my site in there instead...
//document.getElementById('searchResults').value = result
console.log("callback compelete");
},
error: function(error) {
console.log("callback Error");
}
});
});
}
Server-Side: (on page load)
//holds actions from page
string payload = HttpContext.Current.Request.Form["payload"] ?? String.Empty;
// See if there were hidden requests (callbacks)
if (!String.IsNullOrEmpty(payload))
{
string temp_AggregationId = CurrentMode.Aggregation;
string[] temp_AggregationList = temp_AggregationId.Split(' ');
Perform_Aggregation_Search(temp_AggregationList, true, Tracer);
}
else
{
HttpContext.Current.Session["SearchResultsJSON"] = "";
}
The rest of the server-side code works properly and just handles the parsing of the incoming and performs a search of the db and then parses the search results into a JSON obj.
Currently, the only way the json obj gets written to the page is if I call it without the callback (just call it on page load). Also, in firebug, it looks like the entire page source is posting back as the 'result' of the callback. I do see my json result within the posted back 'result' but it also contains the entire page HTML.
Moreover, I can't seem to get the result to post to the page which is the whole point. Actually, I could get the result to post to the page by simply uncommenting that bit in the client side code but it posts a copy of my site and not the actual result I thought I created...
What am I missing? How do you explicitly state in the C# code what is returned to the JS callback as 'result'?
You get the entire page because you're making a request to an ASP.NET page. In fact, you're requesting the vary same page you're viewing. The server is returning what it would return if you were submitting a form.
To get JSON data, you need to create a web method to handle your request. Read this article, it will help you. It shows you how to return simple text, but you can return JSON too. Information on this MSDN article.
Finally, to make sure jQuery is parsing the server response as JSON, change your request and indicate it explicitly:
function toServer(data) {
var dataPackage = data + "~";
jQuery('form').each(function () {
document.getElementById('payload').value = JSON.stringify({ sendData: dataPackage });
$.ajax({
type: "POST",
async: true,
url: window.location.href.toString(),
data: jQuery(this).serialize(),
dataType: 'json',
success: function (result) {
//this does not work because it just puts an entire source code copy of my site in there instead...
//document.getElementById('searchResults').value = result
console.log("callback compelete");
},
error: function(error) {
console.log("callback Error");
}
});
});
}

Sending a simple bool value from javascript to a c# web service

[I realise this might seem like a stupid question but I am lost.]
Using umbraco 4.9 I have a multi-lingual site where I have made an event handler to replicate content nodes to all languages as they are created in the back office to all languages. I am now trying to attach this to a custom context menu item(umbraco.interfaces.IAction) to give the creator a choice.
In the context menu item it is only possible to call a javascript function as a string. I shouldn't touch the umbraco code itself so how can I pass a value to a web service? Where do I include the reference?
This is what I have at the moment:
public string JsSource
{
get
{
return "function AddItem(){" +
"var multiLang = confirm('Create for all languages?');" +
//"$.ajax({" +
//"type: 'Post'," +
//"url: 'TryAgain.aspx/' + SendMultiVal" +
//"data: multiLang})" +
//"PageMethods.SendMulti(multiLang);}" +
string.Format("{0}.actionNew()", ClientTools.Scripts.GetAppActions)+"};";
}
}
Thanks in advance.
So the first thing that you need to do is to store the boolean value in a variable called boolvalue and then call the callservice function once you have the value.For eg:
CallService("POST", "YourServiceUrl",boolvalue,
function (data) {
alert("Service Call Success");
},
function (result) {
alert('Service call failed: ' + result.status + '' + result.statusText);
});
This will make a service call and get data from service if it returns some data.
CallService = function (method, serviceUrl, value, successHandler, errorHandler) {
$.ajax({
type: method,
url: serviceUrl,
contentType: "application/text; charset=utf-8",
dataType: "json",
data:JSON.stringify(value),
success: successHandler,
error: errorHandler
});
};
Modify the dataType and dataType fields depending upon the type of data that you send and receive from the service.
Look into this if you need more information:
http://api.jquery.com/jQuery.ajax/
Let me know if this works out for you.

Getting wrong Url.PathAndQuery

I have an action link:
#Html.ActionLink("Shopping cart", "Index", "Cart", new { returnUrl = Request.Url.PathAndQuery }, null)
and code that adds items to cart:
<script type="text/javascript">
$(document).ready(function () {
$("#addToCart_#(Model.ProductID)").click(function () {
var quantity = $("#Quantity_#(Model.ProductID)").val();
var productId = "#Model.ProductID";
var dataToBeSent = { 'quantity': quantity, 'productId': productId};
$.ajax({
type: "POST",
url: '/Cart/AddToCart/',
data: dataToBeSent,
success: function (result) {
$('#cartholder').html(result);
}
});
});
});
</script>
When I'm trying to follow action link after adding item to cart, Request.Url.PathAndQuery has value /Cart/AddToCart/.
How can I get current url?
You need to use:
Request.RawUrl
This will get the URL you see in the browser. When using Url writing as with MVC the Request.Url will be the rewritten path.
Looks to me like you are setting your URL to /Cart/AddToCart/. It's right there in your AJAX request: url: '/Cart/AddToCart/'. That's it -- that's your URL (not counting the scheme and host).
You're specifying type: "POST", so your payload (your data: dataToBeSent) isn't sent as part of the URL. The data only gets sent in the URL when you use GET. When you use POST, it's in the request body, not the URL.
(And don't just change it to a GET. It would seem to work for now, but would give you headaches later. GET requests can be cached by proxy servers -- not appropriate for requests that modify state, like adding things to a shopping cart.)
So in answer to the question you asked, Request.Url.PathAndQuery is how you get the URL. It's just that the URL is not what you want. You want to get your POST data, however that's normally done in ASP.NET MVC.
System.Web.HttpContext.Current.Request.Url

Ajax post error

I want to post data to a web service with ajax. there is my ajax code:
function Looping() {
var Grid = document.getElementById("<%= gvHastalar.ClientID %>");
var Row;
var Cell;
if (Grid.rows.length > 2) {
for (i = 1; i < Grid.rows.length - 1; i++) {
Row = Grid.rows[i];
Cell = Row.cells[3];
alert(Cell.innerHTML);
var html = $.ajax(
{
type: "POST",
url: "http://localhost:7753/HastaTahlilUyariServisi.asmx/f_HastaninAktarilacakAlislabTestleri",
data: "{_sTcKimlikNo:" + Cell.innerHTML + ",_iKlinikKodu:18001,_bAy:12,_iYil:2009}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: alert('success'),
error: alert('error')
}
).responseText;
Row.style.backgroundColor = "#D3EFD1";
}
}
}
And my webservice function's code is here:
[WebMethod]
[SoapHeader("_ticket", Direction = SoapHeaderDirection.In)]//SoapHeaderDirection.Out
public DataSet f_HastaninAlisLabTahlilleri(string _sTcKimlikNo, int _iKlinikKodu, byte _bAy, int _iYil)
{
try
{
string QSelect =
#"SELECT * FROM [V_EUCLID_SONUC]
WHERE MONTH(KAYITTARIHI) = " + _bAy + #"
AND YEAR(KAYITTARIHI) = " + _iYil +
AND TCKIMLIKNO = '" + _sTcKimlikNo + #"'";
return dbA.ExecuteDataSet(CommandType.Text, QSelect);
}
catch (Exception ex)
{
throw (ex);
}
}
There is a break point on function which is in the web service but debug never go that break point. I pasted webservice's url from browser but may be url is wrong. And when i run project, i have 3 alert.
First Cell's text its normal.Second alert is success and the last alert is error. I want to send parameters to f_HastaninAlisLabTahlilleri and user return dataset. How can i do this?
Thanks in advance
Here are a few remarks about your code:
success and error are callback functions, they should be defined like this:
success: function(data) { alert('success'); },
error: function(XMLHttpRequest, textStatus, errorThrown) { alert('error'); }
ASMX web services use SOAP by default unless you decorate them with ScriptServiceAttribute in which case JSON could be used to invoke a method. It is not clear from your code if the web service is decorated with this attribute.
When you pass parameters, you need to encode them, use JSON. stringify instead of concatenating strings:
data: JSON.stringify({_sTcKimlikNo: Cell.innerHTML,
_iKlinikKodu: 18001,
_bAy: 12,_iYil: 2009});
Use FireBug to inspect network AJAX requests and server responses and post them on StackOverflow to facilitate debugging.
You cannot put a break-point in the web-service code i.e. even the IDE would not let u debug the web-service code.... it is an old legacy the VS.Net IDE has since its inception... lets see if it is resolved in VS 2010.
The url that you have specified in the JQuery script is not equal to the name of the function in c# code. Isn't it the point. *f_HastaninAktarilacakAlislabTestleri* in url and *f_HastaninAlisLabTahlilleri* in c# code. Some reasons for such a problem can be wrong url or deference between argument list of client request and argument list of the server side method or action.

Categories