I want to update textarea from controller after i found some result and page should not be reload. Is there any solution for this?
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public JsonResult SolveProblems(Problem[] array){
Solution sol=new Solution(array);
sol.OnSolutionFound+=sol_OnSolutionFound;
sol.OnTaskComplete+=sol_OnTaskComplete;
sol.Start();
return Json("Process started");
}
private void sol_OnSolutionFound(object sender, SolutionFoundEventArgs e)
{
// Here i want update textarea
}
private void sol_OnTaskComplete(object sender, SolutionCompletedEventArgs e)
{
// Here i want show process is finished
}
}
This is my html page. which contains some code and one textarea
..... some code....
<textarea class="form-control" id="ResultDisplay"></textarea>
<button type="button" id="btnSolve" class="btn btn-primary">Solve</button>
this is my javascript file
function GetProblems(){
...code...
return array;
}
$("#btnSolve").click(function () {
$.ajax({
type: "POST",
url: "/Home/SolveProblems",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(GetProblems()),
dataType: "json",
success: function (response) {
},
error: function (response) {
alert("Unexpected error occurs!")
}
});
});
So, I have use SignalR and solve my problem as freedomn-m told me to do
I need to create a Hub by using i can send data when sol_OnSolutionFound is fired.
Here is my Hub
public class SolutionHub : Hub
{
public void SolutionFound(string Solution)
{
var hubContext = GlobalHost.ConnectionManager.GetHubContext<SolutionHub>();
hubContext.Clients.All.addNewMessageToPage(Solution);
}
}
Add section in Index.cshtml
#section scripts {
<!--Script references. -->
<!--The jQuery library is required and is referenced by default in _Layout.cshtml. -->
<!--Reference the SignalR library. -->
<script src="~/Scripts/jquery.signalR-2.2.2.min.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="~/signalr/hubs"></script>
<!--SignalR script to update the chat page and send messages.-->
<script>
$(function () {
// Reference the auto-generated proxy for the hub.
var chat = $.connection.solutionHub;
// Create a function that the hub can call back to display messages.
chat.client.addNewMessageToPage = function (Solution) {
// Add the message to the page.
$("#ResultDisplay").append(Solution);
};
$.connection.hub.start().done(function () {
});
});
</script>
}
and finally need to call SolutionFound when sol_OnSolutionFound is fired.
private void sol_OnSolutionFound(object sender, SolutionFoundEventArgs e)
{
SolutionHub Hub=new SolutionHub();
Hub.SolutionFound(e.Solution);
}
Related
First of all, sorry if I make english mistakes
I'm making this side-project for fun using Vue3 & Vite and it's my first time using Supabase
I created the 'players' table in the Supabase dashboard and added two rows for testing purposes.
I used createClient to initialize the client :
// client.js
import { createClient } from "#supabase/supabase-js"
const supabaseInfos = {
url: "https://example.supabase.co",
key: "example"
}
export const client = createClient(supabaseInfos.url, supabaseInfos.key)
Then I used the client in order to make a Player Controller :
// Player.js
import { client } from "../../lib/client";
export default class Player {
static async index() {
return await client.from('players').select('*')
}
static async show(id) {
return await client.from('players').select('*').match({ id })
}
static async create(data) {
return await client.from('players').insert(data)
}
static async update(id, data) {
return await client.from('players').update(data).match({ id })
}
static async delete(id) {
return await client.from('players').delete().match({ id })
}
}
Please take note that I'm using the official documentation
The main problem is, it doesn't work. The client isn't fetching any data, what it all do is returning an empty array.
// App.vue
<template>
<ul v-if="players.length > 0">
<li v-for="player in players" :key="player.id">{{ player.name }}</li>
</ul>
<p v-else>No player found.</p>
</template>
<script>
import Player from './assets/controllers/Player'
export default {
data() {
return {
players: []
}
},
methods: {
async getAllPlayers() {
const { data } = await Player.index()
this.players = data
console.log(data) // returns an empty array
console.log(this.players) // returns an empty Proxy object
}
},
mounted() {
this.getAllPlayers()
},
}
</script>
I really don't understand why the client never returns anything. I got the api key and url right and my database is public. It returns a 200 code but there's nothing to use when the Promise comes
Instead of using createClient, I instanciated a SupabaseClient, which changed nothing at all. I also tried to use client.query() but it didn't work either...
I made a calendar in a Razor page, and I want to make each date (a div) clickable so they call a method and pass it the clicked date (div id set to date). I'm generating the calendar in the cs page and I'm not using MVC controllers.
#model Budget.Pages.CalendarModel
#{
ViewData["Title"] = "Calendar";
}
<form method="post">
#Html.Raw(Model.getCal())
</form>
And then in my cs page I have the method getCal() that generates a calendar via divs, css and some math, which is working fine, but I need to attach onClick events to each day (div).
public string getCal()
{
//I won't print out all of my calendar generation code in ordfer to simplify this question.
//The code below happens in a loop where the MM, DD and YYYY change as appropriate to be
//unique. This is where I want to put my onclick events to call another method, onDateSelect(this.id)
retValue += "<div id='" + MM + "_" + DD + "_" + YYYY + "' class='col-md-9 dayCell'>" +
strDayNo +
"</div>";
return retValue; //When out of loop of course
}
After rendering the content with #Html.Raw(Model.getCal()) in your page , you can add click event on your div :
#section Scripts{
<script>
$(document).on('click', ".dayCell", function () {
});
</script>
}
Razor Pages are designed to be protected from (CSRF/XSRF) attacks. Hence, Antiforgery token generation and validation are automatically included in Razor Pages. Please refer to below article for code sample :
Handle Ajax Requests in ASP.NET Core Razor Pages
Here is code sample based on your requirement :
#section Scripts{
<script>
$(document).on('click', ".dayCell", function () {
$.ajax({
type: "POST",
url: "/YourPageName?handler=Send",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: JSON.stringify({
ID: this.id
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
},
failure: function (response) {
alert(response);
}
});
});
</script>
}
Server side function :
public JsonResult OnPostSend([FromBody]PostData value)
{
....
}
public class PostData
{
public string ID { get; set; }
}
Also configure the antiforgery service to look for the X-CSRF-TOKEN header:
services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
Forgive my bad english.
I have a project that contains signalR and JavaScript code. But the controller side called Clients.All.function_name (); not working.
My hub class:
public class yenile : Hub
{
public void sayfaYenile()
{
Clients.All.syenile();
}
}
My javascript code:
<script>
var sayfayenile = $.connection.yenile;
sayfayenile.client.syenile = $(function () {
$.ajax({
type: "GET",
url: '/hasta/',
data: {},
success: function (data) {
$("#con").html($(data).find("#con").html());
},
}
});
});
$.connection.hub.start().done(function () { console.log("connected"); });
</script>
IHubContext
public static IHubContext yenileContext = GlobalHost.ConnectionManager.GetHubContext<yenile>();
And calling the yenileContext
yenileContext.Clients.All.yenile();
My Startup class:
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
Kindly you must refer signalr library files.Depend on your signlar verions you should change.
<!--Reference the jQuery library. -->
<script src="Scripts/jquery-3.1.1.min.js" ></script>
<!--Reference the SignalR library. -->
<script src="Scripts/jquery.signalR-2.2.1.min.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="signalr/hubs"></script>
Second point: Your javascript reference must use camel case for calling your server class and its members function.
I found the cause of the error.
sayfayenile.client.syenile = $(function () instead of
sayfayenile.client.yenile = $(function ()
I have a problem with ajax, play framework 2.1.1:
My Play Project
routes:
POST /sample/testapi controllers.Application.testapi()
GET /sample/ajax controllers.Application.ajax()
Application.java
public static Result testapi() {
DynamicForm dynamicForm = DynamicForm.form().bindFromRequest();
String data= dynamicForm.get("data");
Logger.debug(data);
return ok("<user no='1'><id>1</id><name>Peter</name></user>");
}
public static Result ajax() {
return ok(ajax.render());
}
When I call action "testapi" from ajax.scala.html through ajax
My ajax code
$.ajax({
url : "http:// localhost:3333/sample/testapi",
type: 'POST',
data: {data: "test"},
dataType: "text",
success : function(result) {
alert(result);
},
error : function(request,error) {
alert(error);
}
});
It working fine.
And I have a html file and I call to play project through ajax.
The action had been called, but not return result and show alert "error".
Please help me. Thanks.
I added "response().setHeader("Access-Control-Allow-Origin", "*");" to my action.
public static Result testapi() {
response().setHeader("Access-Control-Allow-Origin", "*");
DynamicForm dynamicForm = DynamicForm.form().bindFromRequest();
String data= dynamicForm.get("data");
Logger.debug(data);
return ok("<user no='1'><id>1</id><name>Peter</name></user>");
}
"response().setHeader("Access-Control-Allow-Origin", "*");" allow other domain call it.
I have a simple MVC4 app where however I want to combine knockoutJS and SignalR and I got a challenge which seems to be caused by the fact that I'm trying to assign 2 onclick events on the same button: using knockoutJS and signalR. Please let me know what's wrong here. Below is the code.
This is my viewModel:
var viewModel = {
searchString: ko.observable("Monique"),
search: function () {
$.ajax({
url: "#Url.Action("Search")",
type: "post",
data: ko.toJSON(this),
contentType: "application/json",
success: function (result) {
$('#info').append(result.message);
}
});
},
searchClient: function () {
//do sth
},
showAll: function () {
//do sth
}
};
ko.applyBindings(viewModel);
And this part is related to signalR:
This is my hub on a server:
[HubName("send")]
public class DataHub: Hub
{
public void Send(string text)
{
Clients.All.addMessage(text);
}
}
and this is a signalR js part:
$(function () {
var hub = $.connection.send;
hub.client.addMessage = function (text) {
alert(text);
$('#info').append(text);
};
$.connection.hub.start().done(function () {
$('#btnServer').click(function () {
alert('btn server clicked');
hub.server.send("something");
});
});
});
So as you can see, knockoutJS has onclick event processing here search: function () { }
and in signalR I also have $('#btnServer').click(function() {.
And as a result, what is related to knockoutJS works but the part related to signalR does not work...
In that function where you bind click event using knockout, return true. By default, Knockout will prevent the click event from taking any default action.