URL in $.post with multiples websites - c#

I have a JavaScript to fill my address
$.post('/Endereco/getEnderecos', { CardCode: dado }, function (data) {
if (data) {
(...)
My problem is: if i publish my website in 'localhost',works,but if i publish my website in "localhost/site" not work, is the same to "www.mydomain.com" and "www.mydomain.com/site"
My website is Development in C# asp.net MVC3 IIS7
i have tried use the javascript to get the host, but not work
Thanks

You have a leading slash in your address /Endereco/getEnderecos, this will cause the browser to navigate to the root of the current host and then the URL you have provided.
For example, posting to /somePage from a page at www.mysite.com/folder/subfolder/page will post to the url www.mysite.com/somePage.
To rectify this, remove the slash from before Endereco, so your post looks like this:
$.post('Endereco/getEnderecos', { CardCode: dado }, function (data) {
if (data) {
(...)
In response to your comment, you could instead use the .. notation which means "go up a folder":
$.post('../../Endereco/getEnderecos', { CardCode: dado }, function (data) {
if (data) {
(...)
From localhost/order/Endereco/getEnderecos your resulting URL would be localhost/Endereco/getEnderecos, as we used two .. components, it has gone up two folders instead of one.
I was looking for some kind of tutorial on relative URLs and found this page: http://www.webreference.com/html/tutorial2/3.html. It might help you to better understand HTTP URLs =]

Related

Display consistently changing value on an ASP.NET web form

I am currently writing a program in C# that constantly outputs random values between 1 and 12 and displays them in a label control on an ASP.NET web form. While the output is successfully written to the web form, it only displays one value. In other words, I want the label output to track the output (display) each value that is produced by the function as written below to produce a consistently changing value:
[WebMethod]
public static string StreamData()
{
string[] value = new string[1];
Random rnd = new Random();
Thread t = new Thread(delegate ()
{
while (true)
{
value[0] = rnd.Next(1, 13) + "";
}
});
t.Start();
return value[0];
}
I have tried using an AJAX function to pull the data from the function but I am not too sure if I am going about displaying the data in the right way:
<script type="text/javascript">
$(function () {
$.ajax({
type: 'POST',
url: 'default.aspx/streamdata',
data: '',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
//alert(msg.d);
$('#<%= lblReading.ClientID %>').html(msg.d);
}
});
});
</script>
The program is being written to test the concept of trending live data from PLCs using TIA Portal 15 with said data obtained from sensor readings across a production line. The idea behind this program is to serve as a proof of concept that real-time data can in fact be displayed and trended in an ASP.NET web environment to be accessed across a range of web-compliant devices. Despite my efforts in displaying random values in this way, my attempts have been thus far unsuccessful, although I am determined to not give up. I researched this method which uses SignalR to achieve something similar to my desired solution, though I am unsure of how to implement it in my case: How to implement real time data for a web page
Could somebody please shed some light on how the above might be achieved?
Many Thanks,
Ben.
Your requirement can be accomplished in ASP.Net web forms using SignalR.
Please take a look at this small tutorial on how to do that,
Adding SignalR to an ASP.NET WebForms Project

PDF thrown to browser console, not downloading

I'm using Rotativa to generate a PDF file from a view, which works well, but now on the browser I get the raw file thrown at the console, no download dialog box, no warning, nothing. Here's my code:
Controller
public ActionResult DescargarPDF (int itemId) {
var presupuesto = ReglasNegocio.Fachada.Consultas.ObtenerPresupuesto(itemId);
return new Rotativa.PartialViewAsPdf("_PresupuestoFinal", presupuesto) {
FileName = "Presupuesto_" + itemId + ".pdf",
PageSize = Rotativa.Options.Size.A4
};
}
JQuery script:
$(".convertirPDF").on("click", function (id) {
var itemId = $(this).data('itemid');
Pdf(itemId);
});
function Pdf(itemid) {
var id = itemid;
$.ajax({
method: "POST",
url: 'DescargarPDF',
data: { itemId: id },
cache: false,
async: true,
});
};
Button on the HTML
<button class="convertirPDF btn btn-secondary btn-info" data-itemid="#item.Id">PDF</button>
I've tried several codes on the controller (with same result) since the script and view seems to work fine. However, I'm suspecting, maybe the html or the script need some tuning to inform the browser it has to download the file?
Thanks everyone in advance.
I found a solution. It's not elegant, but it works.
So I didn't need to use ajax necessarily to make the request, neither to give function to the button. I'm kind of sure that the issue has something to do with JS and/or jQuery. Nevertheless, there's a simpler way to do this.
I changed my html button to:
PDF
so it looks like a button but it's really a link to my controller¡s method. I also removed the script for that button and now it downloads the file. Not with the name intended, but still.
Thanks to everyone. Happy coding.
UPDATE
I've been working on the same project, and I think I found out why my PDF file was being thrown into console.
The thing is, jQuery makes the request, so jQuery manages the response. Is that simple. If you check official docs for .post(), you'll see the following:
The success callback function is passed the returned data, which will be an XML root element or a text string depending on the MIME type of the response. It is also passed the text status of the response.
As of jQuery 1.5, the success callback function is also passed a "jqXHR" object (in jQuery 1.4, it was passed the XMLHttpRequest object).
Most implementations will specify a success handler.
And I wasn't, so, by default, it just drop it to console. I hope this throws some light into the issue and helps. Happy coding.

Sharing cookies between domain and a subdomain using IIS express

I'm trying to share a cookie between two ASP.NET mvc 6 apps :
The first one is a web api app and it should represent the main domain "localhost".
Second one is an empty mvc website client app, with one index.html that calls the web api via simple ajax. this app represents the subdomain "cleint.lohalhost".
For somereason, my browser is unable to set the cookie on the client app. Details below :
-Set cookie header generated by web api
Set-Cookie:mytoken=mytokenvalue; domain=.localhost; path=/; samesite=lax
-Ajax call :
$.get({
url: 'http://localhost:5004/api/values',
success: function (response) { console.log(response); },
error: function (error) { console.log(error); },
xhrFields: {
withCredentials: true
},
crossDomain: true
});
-And finally, the code that sets the cookie on the web api app :
[HttpGet]
public IEnumerable<string> Get()
{
Response.Cookies.Append("mytoken", "mytokenvalue", new CookieOptions() { Domain = ".localhost" });
return new string[] { "value1", "value2" };
}
-I use chrome browser if it's relevant.
I appreciate any kind of help, thank you.
It turned out my browser was still hungry for another '.' on the domain name, so I ended up replacing 'localhost' (on both domain names) with 'myapp.dev' and it worked.
It is also important to note that from the api side, I had to send the domain name cookie option with the value '.myapp.dev' instead of 'client.myapp.dev'

Uploaded site to IIS, cannot find controller resource (error 500). Works locally using iisexpress

Been doing lots of testing and eventually got everything working in Visual Studio using iisexpress. I've deployed it into IIS via a web package.zip and now my function has stopped working. Any thoughts? Event viewer isn't reporting anything.
I click the button to call the ajax - the GET looks like it is properly formulated but it can't find something - I'm guessing the 'GetData' method. Do I need to change the URL.Action in the project before deploying? (Tried with and without content-type, hence the comment tags)
Ajax call
<script>
$("#button").click(function (event) {
event.preventDefault();
var uquery = $('#HospitalID').val();
var url = '#Url.Action("GetData", "oncologyPatients")';
//alert(uquery); //ENABLE FOR ERROR CHECKING OF VARIABLE
var data = { value: uquery }
$.ajax(
{
url: url,
data: data,
type: 'GET',
//contentType: "application/json; charset=utf-8",
success: function (data)
{
$('#HospitalID').val(data.HID);
$('#NHS_No_').val(data.NHS);
$('#Forename').val(data.Fname);
$('#Surname').val(data.Sname);
$('#DOB').val(data.DOB);
},
error: function (xhr, status, error)
{
alert(status);
alert(error);
var err = xhr.responseText;
alert(err);
}
});
});
Click the button and locally it finds the 'GetData' in the controller and works fine. However, it throws a very generic error when running on IIS 8.5/Server 2012 R2 and I have to go into the dev. tools of Chrome to get something meaningful which is:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
http://siteuat.local.com/oncologyPatients/GetData?value=11111111
Any ideas, I'm leaning towards absolute URL but it looks as though the route is correct.
All other functions are fine - it's basically just this one call that is having problems.
Figured this out a few minutes after posting - grrr. It was working locally because my user account had permissions to make a TrustedConnection to the database (which I didn't need).
My sqlConnection looked like this:
SqlConnection DWLKup = new SqlConnection("user id=user;" +
"password= password;server=Server\\Instance;" +
"Trusted_Connection=yes;" +
"database=db1; ");
I removed the
"Trusted_Connection=yes;" +
And it's all working now :)

Nancyfx Request.Session not holding values on AJAX post

I'm quite new to Nancy so hopefully I'm just doing something silly here. I've got a nancy service which I'm posting data to like so:
$.ajax({
type: 'POST',
url: url,
data: JSON.stringify({
searchTerm: productSearchTerm,
pageSize: pageView.PageSize(),
selectedBrands: pageView.checkedBrands(),
pageNumber: pageView.CurrentPage(),
selectedCategories: pageView.checkedCategories(),
selectedGender: pageView.checkedGender(),
SelectedColours: pageView.checkedColour(),
saleItemsOnly: pageView.saleItemsOnly(),
selectedMinimumPrice: pageView.minPrice(),
selectedMaximumPrice: pageView.maxPrice()
}),
contentType: "application/json; charset=utf-8",
dataType: 'json'
})
.done(function (data) {
bindSearchResult(data);
})
.fail(function (a) {
console.log(a);
});
Then in the service I need to hold on to a bunch of string values for future requests from the user, which I'm doing like this:
private void AddListOfStringToIsSessionNull(string name, IEnumerable<string> data)
{
if (Session[name] == null)
{
Session[name] = data.ToList();
}
}
These seems to set the session variables and an "_nc" cookie is present when I inspect the page after it returns.
However if I then F5 the page the session items are all null again at the server.
I've ruled out are cross site posting as it's all on the same domain.
Could this be an AJAX thing? Seems unlikely as this seems a pretty standard thing to do.
Or can you not set it on a POST?
If so is there a way around this?
If someone could help I'd be forever grateful as otherwise I'm going to have to revert back to writing this in WCF which will make me hurl myself from the window :)
Thanks a lot.
Edit
Open a new incognito window in Chome I hit home page, no nancy cookie
present (which is correct)
Enter a search term which calls back over and AJAX post and grabs JSON, also pops a list of strings in the Nancy Session
Check cookie, a nancy one has appeared like so and the session value is correct on post back:
npTBnqPp99nLd5fU0%2btJbq%2fY%2bdf2UFWTaq5D28Az7Jw%3dzF8cIHNxTWX399sbmowjheho2S29ocpKs1TXD51BrbyPPNCeLfAcYqWhkRHqWdwKJNED5kuspllIjhI5rf2W6NKtf8xo68BlF5eLLgJxMtAxw2yD2ednEzUazq1XBt2Id77t5LE5tZVwkpRGDT5b9J0nQnr9zfzCOALXb2hQQGBPkMVyNNTO24pW1UC6Uda3B86LLYA02Jgy4G9DiT6KsutR3pSXO8AZFOlcmAEHbSSX9A8FAHaL ... etc.
I then search for a different search term which calls this bit of code:
--Session.DeleteAll();
The nancy session is re-populated with new data and returns back to the browser
However at this point the cookie has not been updated with the new value it is still as below:
npTBnqPp99nLd5fU0%2btJbq%2fY%2bdf2UFWTaq5D28Az7Jw%3dzF8cIHNxTWX399sbmowjheho2S29ocpKs1TXD51BrbyPPNCeLfAcYqWhkRHqWdwKJNED5kuspllIjhI5rf2W6NKtf8xo68BlF5eLLgJxMtAxw2yD2ednEzUazq1XBt2Id77t5LE5tZVwkpRGDT5b9J0nQnr9zfzCOALXb2hQQGBPkMVyNNTO24pW1UC6Uda3B86LLYA02Jgy4G9DiT6KsutR3pSXO8AZFOlcmAEHbSSX9A8FAHaL.... etc.
Is there anything else I need to do to solve this?
So my issue was me being a bit daft really, the implementation of the cookie stuff works well, however there were occasions when I was stuffing too much into the cookie and pushing it over the 4K cookie limit.
This meant that I was seeing some inconsistent behavior where sometimes the cookie worked nicely (the cookie was < 4K) where as for some search terms too much was being written into the cookie which meant either the cookie was never created or it was not overwriting the existing cookie.
So yes, my fault, but thought this answer might aid someone as silly as me trying to store the world in a cookie..
Right I'm off to write a session provider.

Categories

Resources