C
C#ā€¢10mo ago
0x05962

ā” post req controller

[HttpPost] public IActionResult StockData(string stockTicker){ _logger.LogInformation("StockData action invoked with stockTicker: {StockTicker}", stockTicker); return View("Privacy"); } no errors but the url doesn't change when return View happens
47 Replies
0x05962
0x05962ā€¢10mo ago
and the logInformation print are good
Angius
Angiusā€¢10mo ago
Why would the URL change?
0x05962
0x05962ā€¢10mo ago
still here? made significant changes now and so
"use strict";

$("#getStockPriceBtn").click(function () {
var stockTicker = $("#stockTicker").val();
console.warn(stockTicker);

var xhr = new XMLHttpRequest();
xhr.open("POST", "/Home/StockData", false); // Third parameter is "false" for synchronous request
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

var formData = "stockTicker=" + encodeURIComponent(stockTicker);

try {
xhr.send(formData);
if (xhr.status === 200) {
console.warn("good");
// Navigate to Privacy only after the synchronous request completes
// window.location.href = '/Home/Privacy';
} else {
console.error("Error:", xhr.statusText);
}
} catch (error) {
console.error("Error:", error);
}
});
"use strict";

$("#getStockPriceBtn").click(function () {
var stockTicker = $("#stockTicker").val();
console.warn(stockTicker);

var xhr = new XMLHttpRequest();
xhr.open("POST", "/Home/StockData", false); // Third parameter is "false" for synchronous request
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

var formData = "stockTicker=" + encodeURIComponent(stockTicker);

try {
xhr.send(formData);
if (xhr.status === 200) {
console.warn("good");
// Navigate to Privacy only after the synchronous request completes
// window.location.href = '/Home/Privacy';
} else {
console.error("Error:", xhr.statusText);
}
} catch (error) {
console.error("Error:", error);
}
});
[HttpPost]
public IActionResult StockData(string stockTicker){
_logger.LogInformation("StockData action invoked with stockTicker: {StockTicker}", stockTicker);

return RedirectToAction("Privacy");
}
[HttpPost]
public IActionResult StockData(string stockTicker){
_logger.LogInformation("StockData action invoked with stockTicker: {StockTicker}", stockTicker);

return RedirectToAction("Privacy");
}
there is no url redirection in the controller when i test
Angius
Angiusā€¢10mo ago
XHR šŸ’€ So, uh, I haven't used XHR since the early 2000s, do you... get the data returned from the request anywhere? Because, yeah, the API controller redirects to another one But that won't reload the page or anything like that
0x05962
0x05962ā€¢10mo ago
doesn't have to be XHR
Angius
Angiusā€¢10mo ago
I mean, XHR or not, just hitting up a controller that redirects somewhere will have no effect on your frontend
0x05962
0x05962ā€¢10mo ago
Basically I'm trying to do server side redirect or change to another view Oh wut Maybe I don't understand how this stuff works
Angius
Angiusā€¢10mo ago
Possibly
0x05962
0x05962ā€¢10mo ago
So how does return view work then
Angius
Angiusā€¢10mo ago
If everything is rendered server-side, then yes, redirecting to a different controller will actually navigate to that different controller But when you call a controller from Javascript, it can be redirecting 172 times And the JS code will follow, yeah But the page showed in the browser will not
0x05962
0x05962ā€¢10mo ago
Ah so do the redirection in controller and uh js also?
Angius
Angiusā€¢10mo ago
JS is specifically used to avoid having to reload the page
0x05962
0x05962ā€¢10mo ago
Oh
Angius
Angiusā€¢10mo ago
As a side note, yeah, XHR is a relic of the past Use fetch unless you have a gun to your head
0x05962
0x05962ā€¢10mo ago
Lol I tried xhr for synchronus What's better Asynchronus js or synchronous js
Angius
Angiusā€¢10mo ago
If something can be done asynchronously it's probably for good reason
0x05962
0x05962ā€¢10mo ago
So it's not needed?
Angius
Angiusā€¢10mo ago
What's not needed? Asynchronous code? It probably is needed Going out of your way to use decades-old technology just to force something to be synchronous? Unnecessary and outright detrimental
0x05962
0x05962ā€¢10mo ago
Oh lol But also what I don't understand is If client is doing post req to server And server is returning viee How come the client view doesn't update
Angius
Angiusā€¢10mo ago
Because it's the JS code that runs the request and receives the response Not the browser You can think of it like the Javascript code opening a hidden browser window in the background
0x05962
0x05962ā€¢10mo ago
Not sure what that really means You're saying it's the client doing it?
Angius
Angiusā€¢10mo ago
Yes Javascript makes requests in its own little world And gets them in their own little world And if you want any of that to influence what's shown in the broswer, you need to do that explicitly
0x05962
0x05962ā€¢10mo ago
So it's not possible to do whst I'm doing Well trying
Angius
Angiusā€¢10mo ago
Because... the controller redirects the javascript to a different view/controller/page/whatever It does not redirect the browser
0x05962
0x05962ā€¢10mo ago
Oh bruh wth šŸ’€
Angius
Angiusā€¢10mo ago
If you want it to open a new page in the browser with new data and what not, just use a form
0x05962
0x05962ā€¢10mo ago
You got a YouTube video explaining that
Angius
Angiusā€¢10mo ago
As I said, JS is usef specifically to avoid reloading/redirecting/moving away from the current page
0x05962
0x05962ā€¢10mo ago
Ohhh I get it's purpose now So what's the point of making a post to a controller
Angius
Angiusā€¢10mo ago
??? To... send data there?
0x05962
0x05962ā€¢10mo ago
Yeah Just for storing? Like database
Angius
Angiusā€¢10mo ago
uh Yeah, for example
0x05962
0x05962ā€¢10mo ago
The reason why I wanted to do whst I wanted btw was to return the view with data Cause it'd be easy But ig I can use signal r for that
Angius
Angiusā€¢10mo ago
SignalR will work the same way an API would Just real-time
0x05962
0x05962ā€¢10mo ago
Is there a better way to pass information to other views Without database
Angius
Angiusā€¢10mo ago
I mean, you can continue using the API But you will have to handle what it returns yourself Not count on the page updating automagically
0x05962
0x05962ā€¢10mo ago
What api Signalr?
Angius
Angiusā€¢10mo ago
No An API That you make yourself With controllers Like you have it now
[ApiController]
[Route("[controller]")]
public class WhateverController : ControllerBase
{
[HttpPost]
public ActionResult<string> PostData(int id, string name)
{
var str = $"There is {id} of {name}";
await File.WriteAllTextAsync("data.txt", str);
return Ok(str);
}
}
[ApiController]
[Route("[controller]")]
public class WhateverController : ControllerBase
{
[HttpPost]
public ActionResult<string> PostData(int id, string name)
{
var str = $"There is {id} of {name}";
await File.WriteAllTextAsync("data.txt", str);
return Ok(str);
}
}
<button id="btn">Click me!</button>
<input id="num" type="number" />
<input id="name" type="text" />
<div id="data"></div>
<button id="btn">Click me!</button>
<input id="num" type="number" />
<input id="name" type="text" />
<div id="data"></div>
const btn = document.getElementById('btn');
const num = document.getElementById('num');
const name = document.getElementById('name');
const data = document.getElementById('data');

btn.addEventListener('click', async () => {
const res = await fetch('/whatever', {
method: 'POST',
body: JSON.stringify({
id: num.value,
name: name.value
})
});

const data = await res.json();
data.innerText = data;
});
const btn = document.getElementById('btn');
const num = document.getElementById('num');
const name = document.getElementById('name');
const data = document.getElementById('data');

btn.addEventListener('click', async () => {
const res = await fetch('/whatever', {
method: 'POST',
body: JSON.stringify({
id: num.value,
name: name.value
})
});

const data = await res.json();
data.innerText = data;
});
Here's an example Now, mind you, I just wrote it here, on Discord, so it's untested and might contain errors lol
0x05962
0x05962ā€¢10mo ago
Where do I save the data to
Angius
Angiusā€¢10mo ago
In this case, to a file
Angius
Angiusā€¢10mo ago
Angius
Angiusā€¢10mo ago
Ideally, to a database
0x05962
0x05962ā€¢10mo ago
Ohhh yeah makes sense Ty for the understanding lol Would've never understood that can u help
Angius
Angiusā€¢10mo ago
With?
0x05962
0x05962ā€¢10mo ago
0x05962
0x05962ā€¢10mo ago
Viewbag being null in html but being aapl in the controller
Accord
Accordā€¢10mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server
More Posts
ā” Setting up a One-To-Many-Relationship in EntityFramework Core```cs namespace GetOut.Models; public class Provider(string slug, string name, string? description)ā” Getting a wrong result on LeetCode although the IDE shows the correct outputSo I believe I still make some mistake in setting cows' Count for this puzzle https://leetcode.com/pā” šŸž Getting a wall of `MSB3030` every other call to `publish`Hi all, I'm working on a `dotnet` project that has an `npm` front-end that gets pre-built and throwā” Maybe Disposable ObjectI want to have a function that returns an HttpClient or an error. The function would take in JSON Aā” 3D Arrays = good tutorial?Does someone have a good guide/tutorial how to explain 3d arrays. the course on udemy isnt to clear ā” Blazor - Component button with different event depending on the page that call itHi, I have a component that has 4 buttons (Open, Save, Clear, Run), and this component is used in ā” C# WPF ListView - How do you create expanded info on selection of a ListView Element?I'm new to WPF and have decided to learn by creating a little tracker for the game Escape From Tarkoā” EFCore, help with atomic update along with complex conditionsBasically, I've been trying to do something like this... ```cs var composite = await _dbContext.Invā” Display error message if value out of limitHi, i'm using wpf with mvvm pattern and i'd like to know if it's good to do this in order to displayā” project planningIs youtrack any good or do you recommend a different project planning tool? Would love ide integrat