I'm writing multiplayer game (Monopoly) in ASP and SignalR.
I've stopped on page which contains a table with list of games.
I have no idea if I'm doing it right:)
So, this is what I've done so far and I need help to move on:
I created GamesList WebForm page with empty table:
<table id="gamesTable">
<thead>
<tr>
<th>#</th>
<th>Number of players</th>
<th>Players</th>
<th>Theme</th>
<th>Join<thead>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
</tfoot>
</table>
My goal is to populate this table when page loads. Data should be provided by hub:
GamesListHub.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using Newtonsoft.Json;
namespace Obipoly.Hubs
{
public class GamesListHub : Hub
{
public List<GamesItem> games = new List<GamesItem>()
{
new GamesItem(2, "Theme1", "User1"),
new GamesItem(4, "Theme3", "User2")
}; //just for tests
public void gamesListUpdated()
{
string gamesString = JsonConvert.SerializeObject(games);
Clients.All.updateGamesList(gamesString); //pass games list
}
public void addNewGame(int numberOfPlayers, string gameTheme, string hostPlayer) {
games.Add(new GamesItem(numberOfPlayers, gameTheme, hostPlayer));
string gamesString = JsonConvert.SerializeObject(games);
Clients.Others.updateGamesList(gamesString);
}
public void getListOfGames() {
string gamesString = JsonConvert.SerializeObject(games);
Clients.Caller.updateGamesList(gamesString);
}
}
}
This is my javascript code on client side in GamesList.aspx:
<script type="text/javascript">
$(function () {
var gamesListHub = $.connection.gamesListHub;
gamesListHub.client.updateGamesList = function (games) {
console.log(games);
};
$.connection.hub.start().done(function () {
gamesListHub.server.getListOfGames();
});
});
</script>
The problem is I get this: "[{}{}]".
How can I pass this list from signalR to JS method to populate the table?
Thanks.
SOLVED:
var gamesJson = $.parseJSON(games);
for (var i = 0; i < gamesJson.length; i++) {
console.log(gamesJson[i].gameTheme);
}
Related
I'm trying to make a web app in Java that connects to a database and shows a table with users.
I have problem with this piece of code in HTML but I believe that this is only the result of earlier coding.
So the code in curly brackets ( {{user.name}} and other) gets underlined and says "Unresolved variable"
I have no idea where is the problem so I'm pasting my angular methods and Java code where I made a list with users that should be displayed in localhost.
This is the code from github that I tried to rewrite but instead of hotels I'm displaying Users.
https://github.com/dangeabunea/RomanianCoderExamples/blob/master/BookingDemo/src/main/resources/templates/index.html
HTML code:
<!-- Display users in a table -->
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Surname</th>
<th>Login</th>
<th>Is Deleted?</th>
<th style="width: 90px"></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in vm.users">
<td>{{user.name}}</td>
<td>{{user.surname}}</td>
<td>{{user.login}}</td>
<td>{{user.isDeleted}}</td>
<td>
<button class="btn btn-danger" ng-click="vm.deleteUser(user.id)">Delete</button>
</td>
</tr>
</tbody>
</table>
JavaScript (angular):
angular
.module('app')
.controller('UserController', UserController);
UserController.$inject = ['$http'];
function UsersController($http) {
var vm = this;
vm.users = [];
vm.getAll = getAll;
vm.deleteUser = deleteUser;
init();
function init(){
getAll();
}
function getAll(){
var url = "/users/all";
var usersPromise = $http.get(url);
usersPromise.then(function(response){
vm.users = response.data;
});
}
function deleteUser(id){
var url = "/users/delete/" + id;
$http.post(url).then(function(response){
vm.users = response.data;
});
}
}
Java:
#Component
public class DatabaseSeeder implements CommandLineRunner {
private UserRepository userRepository;
#Autowired
public DatabaseSeeder(UserRepository userRepository){
this.userRepository = userRepository;
}
#Override
public void run(String... strings) throws Exception {
List <Users> users = new ArrayList<>();
users.add(new Users("John", "Kowalski", "john332", false));
users.add(new Users( "Debby", "Ryan", "debbs84", false));
users.add(new Users( "Michael", "Smith", "grizzly98", false));
userRepository.saveAll(users);
I am new to js programming and attempting to use Datamuse to get some words to use in a hangman program. I have been searching for an example on how to call Datamuse in js but haven't really been able to find anything. Any help is greatly appreciated!
//This is a rudimentary example using MVC .NET that consumes Datamuse API
//Controller Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web;
using System.Web.Mvc;
using DictMVC.Models;
using System.Net.Http.Headers;
namespace DictMVC.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
var client = new HttpClient();
string word = "whittle";
client.BaseAddress = new Uri("https://api.datamuse.com/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("words?ml="+word).Result;
List<WordDefViewModel> words = response.Content.ReadAsAsync<List<WordDefViewModel>>().Result;
ViewData["word"] = word.ToUpper();
return View(words);
}
}
}
// View Model Class
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace DictMVC.Models
{
public class WordDefViewModel
{
[Display(Name = "Meaning")]
public string Word { get; set; }
public int Score { get; set; }
[Display(Name="Parts of Speech")]
public string[] Tags { get; set; }
}
}
// Index View
#model IEnumerable<DictMVC.Models.WordDefViewModel>
#{
ViewBag.Title = "DICTIONARY";
}
<h2>Word Of The Day: #ViewData["word"]</h2>
<table>
<tr>
<th>
#Html.DisplayNameFor(model => model.Word)
</th>
<th>
#Html.DisplayNameFor(model => model.Tags)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Word)
</td>
<td>
#foreach (var tag in item.Tags)
{
#(tag + " ")
}
</td>
</tr>
}
</table>
The following code makes up parts of an ASP.NET MVC application that I am currently working on. The index creates a table that the user can add rows by inputting the values for Tag, Server, and Frequency into a popup modal (activated by hitting the "Add" button, modal HTML code not shown). The table's initial values are currently generated by a migration from a linked SQL Database Table (created by using entity-framework).
I am trying to modify this code so that any rows added by the "Add" button will be automatically added to the linked Database Table (preferably by using entity framework). Any help would be appreciated.
Controller
namespace ExampleWebAppilcationTest.Controllers
{
public class HomeController : Controller
{
ExampleDB _db = new ExampleDB();
public ActionResult Index()
{
var model = _db.TData.ToList();
return View(model);
}
protected override void Dispose(bool disposing)
{
if (_db != null)
{
_db.Dispose();
}
base.Dispose(disposing);
}
}
}
Classes
namespace ExampleWebAppilcationTest
{
public class ExampleDB : DbContext
{
public DbSet<TableData> TData { get; set; }
}
}
namespace ExampleWebAppilcationTest
{
public class TableData
{
[Key]
public String Tag { get; set; }
public String Server { get; set; }
public double Frequency { get; set; }
}
}
Index
#model IEnumerable<ExampleWebAppilcationTest.TableData>
#{
ViewBag.Title = "Home Page";
}
#{
ViewBag.Title = "Index";
}
<h2>Table Data</h2>
<table class="table table-bordered" id="mainTable">
<thead>
<tr>
<th></th>
<th class="thTag" scope="col">
#Html.DisplayNameFor(model => model.Tag)
</th>
<th class="thServer" scope="col">
#Html.DisplayNameFor(model => model.Server)
</th>
<th class="thFreq" scope="col">
#Html.DisplayNameFor(model => model.Frequency)
</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="5">
#foreach (var item in Model)
{
<tr>
<td><input type="checkbox"/></td>
<td>
#Html.DisplayFor(modelItem => item.Tag)
</td>
<td>
#Html.DisplayFor(modelItem => item.Server)
</td>
<td>
#Html.DisplayFor(modelItem => item.Frequency)
</td>
</tr>
</tbody>
</table>
<button type="button" id="addBtn" class="btn btn-success">Add</button>
<!-- The Modals -->
<script>
var table = document.getElementById('mainTable');
// Get the modal
var addmodal = document.getElementById('addModal');
// When the user clicks the button, open the modal
btn.onclick = function () {
addmodal.style.display = "block";
}
var sbtn = document.getElementById("subBtn");
sbtn.onclick = function () {
var table = document.getElementById("mainTable");
var tag = document.getElementById("tag").value;
var server = document.getElementById("server").value;
var frequency = document.getElementById("frequency").value;
var objInputCheckBox = document.createElement("input");
objInputCheckBox.type = "checkbox";
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
cell1.appendChild(objInputCheckBox);
cell2.innerHTML = tag;
cell3.innerHTML = server;
cell4.innerHTML = frequency;
addmodal.style.display = "none";
}
Although you should have a Layered Architecture for your project with separare Business and DataAccess layers and controller should only be the gateway for incoming requests https://learn.microsoft.com/en-us/dotnet/standard/microservices-architecture/microservice-ddd-cqrs-patterns/infrastructure-persistence-layer-design )
This is what you can do with your current adjustment:
Controller:
namespace ExampleWebAppilcationTest.Controllers
{
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
using (var dbContext = new ExampleDB())
{
var model = dbContext.TData.ToList();
return View(model);
}
}
[HttpPost]
public ActionResult Index(TableData data)
{
using (var dbContext = new ExampleDB())
{
dbContext.TData.Add(data);
dbContext.SaveChanges();
}
return RedirectToAction("Index");
}
}
}
Data Access
namespace ExampleWebAppilcationTest
{
public class ExampleDB : DbContext
{
public ExampleDB() : base(nameOrConnectionString: "Your Database Connection String") { }
public DbSet<TableData> TData { get; set; }
}
}
namespace ExampleWebAppilcationTest
{
public class TableData
{
[Key]
public String Tag { get; set; }
public String Server { get; set; }
public double Frequency { get; set; }
}
}
View
sbtn.onclick = function () {
var table = document.getElementById("mainTable");
var tag = document.getElementById("tag").value;
var server = document.getElementById("server").value;
var frequency = document.getElementById("frequency").value;
//Here fetch all data in a class
var data = { Tag: tag, Server: server, Frequency: frequency };
//make ajax call to add data
$.ajax({
type: "POST",
url: '#Url.Action("Index", "Home")', //your action
data: data,
dataType: 'json',
success: function (result) {
//to close the popup
},
error: function (result) {
//to show error message
}
});
}
You need to add an Add method of some sort to your controller, decorated with the POST attribute. In your modal, there needs to be a form pointing to the controller's add method url. The form should contain input fields for all of your table properties. That form should be then posted via a submit button to the add method on your controller. The add method needs to take the properties of the form submitted, create a new object, then insert the new object in to the database.
Hi i invoke a method with using SignalR and i want to use return value as foreach loop in javascript for create a table
Hub :
public void OrderAllSales()
{
List<string> tableValue = new List<string>();
/*
Do something and fill tableValue with
<tr>
<td>....</td>
<td>....</td>
</tr>
block for every item
*/
Clients.All.SendListOfAll(tableValue);
}
Cshtml
<table class="table">
<thead>
<tr style="margin-left: 10px">
<td>Price (₺)</td>
<td>BTC (฿)</td>
<td>Total (₺)</td>
</tr>
</thead>
<tbody id="HistoryGrid">
</tbody>
</table>
JavaScript :
<script>
$(document).ready(function () {
var bitcoinHub = $.connection.bitcoinHub;
$.connection.hub.start().done(function () {
$("#allSales").click(function () {
bitcoinHub.server.orderAllSales();
});
bitcoinHub.client.sendListOfAll(function (x) {
x.forEach(Create);
});
});
function Create(item) {
$("#HistoryGrid").prepend(item);
}
});
</script>
i can invoke server method but i couldn't use this return value for create a table
i figure out it.
Wrong Code :
bitcoinHub.client.sendListOfAll(function (x) {
x.forEach(Create);
});
Right Code :
bitcoinHub.client.sendListOfAll = function (x) {
x.forEach(Create);
};
The error is using () instead of = while trying catch returning method at client side.
Hi i need to get the event id in this table which when the btnStopEvent is clicked its gets the current time and displays it into the same table,i the Endtime Column e.g i have 5 events id 1,2,3,4,5 when the user click the button in column 2 it should display the current time in EndTime Column, Here is what i have for now
function GetStartUserData() {
var IPAddress = $('#IPAddress').text();
(IPAddress == '' ? null : 'ipaddress=' + IPAddress)
var EventId = '';
var Category = $('#categories').val();
var ExtraData = $('#txtcomment').val();
return {
MachineName: IPAddress
, EventId: EventId
, CategoryName: Category
, Comments: ExtraData
}
}
function DisplayStartData(downTimeStart) {
console.log(downTimeStart);
var newContent = '';
$.each(downTimeStart.data, function (i, item) {
newContent += Hesto.Html.StartTR(item.downTimeStart);
newContent += Hesto.Html.CreateTD('<input type="button" value="Stop" id="btnStopEvent">');
newContent += Hesto.Html.CreateTD(item.EventId);
newContent += Hesto.Html.CreateTD(item.CategoryName);
newContent += Hesto.Html.CreateTD(item.StartTime);
newContent += Hesto.Html.CreateTD(item.EndTime);
newContent += Hesto.Html.CreateTD(item.Comments);
newContent = Hesto.Html.EndTR(newContent);
});
$('#DowntimeList').append(newContent);
}
HTML:
<div id="panel"><table id="Downtimetable" class="hesto">
<thead>
<tr>
<th>END OF DOWNTIME</th>
<th>Event ID</th>
<th>CATEGORY NAME</th>
<th>START TIME</th>
<th>END TIME</th>
<th>COMMENTS</th>
</tr>
</thead>
<tbody id="DowntimeList">
</tbody>
<tfoot>
</tfoot>
</table></div>
<div class="label" id="IPAddress"><%Response.Write(Request.QueryString["ipaddress"]); %></div>
json page
using System;
using System.Collections.Generic;
using System.Linq;
using System.Configuration;
using System.Web.Script.Serialization;
using Hesto.SQL;
using Hesto;
public partial class services_json_DownTimeStartByMachineName : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
System.Collections.Specialized.NameValueCollection nvc = new System.Collections.Specialized.NameValueCollection();
nvc.AddFromQueryString(Request.QueryString);
nvc.AddFromQueryString("MachineName", Request.UserHostAddress, Request.QueryString);
nvc.AddFromQueryString("EventId", "NULL", Request.QueryString);
nvc.AddFromQueryString("CategoryName","NULL",Request.QueryString);
nvc.AddFromQueryString("StartTime",DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),Request.QueryString);
nvc.AddFromQueryString("Comments", "NULL", Request.QueryString);
StoredProcedureCaller spc = new StoredProcedureCaller();
spc.Execute(Request.QueryString, Resources.StoredProcedureDefinitions.DownTimeStartTimeByMachineName, Resources.ConnectionStrings.HESTOTESTING);
Response.Write(spc.ToString("json"));
}
}
json page
using System;
using System.Collections.Generic;
using System.Linq;
using System.Configuration;
using System.Web.Script.Serialization;
using Hesto.SQL;
using Hesto;
public partial class services_json_DownTimeStop : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
System.Collections.Specialized.NameValueCollection nvc = new System.Collections.Specialized.NameValueCollection();
nvc.AddFromQueryString(Request.QueryString);
nvc.AddFromQueryString("EventId","", Request.QueryString);
nvc.AddFromQueryString("EndTime", DateTime.Now.ToString(), Request.QueryString);
StoredProcedureCaller spc = new StoredProcedureCaller();
spc.Execute(nvc, Resources.StoredProcedureDefinitions.DownTimeStopEvent, Resources.ConnectionStrings.HESTOTESTING);
Response.Write(spc.ToString("json"));
}
}
You can use onclick method:
<button onclick="myFunction(eventID)">Click me</button>
then you can pass your "event id" to JS part:
function myFunction(eventID){
alert("Your Event ID : " + eventID);
}
or you can use jquery:
$("button").click(function() {
alert(this.id); // or alert($(this).attr('id'));
});
Getting ID of clicked element