how to get the clicked button event id - javascript

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

Related

Passing of model from razor to javascript - very strange error

I tried to pass the selected model in the HTML table row right into javascript function, including conversion to a JSON. The conversion failed because of the problem below.
Also, I freaked out for more than 6 hours trying to understand why it's not working. Now I know what caused the problem, no idea how to fix it.
Here is what I tried (simple and easy):
<table class="table table-hover">
<thead align="center">
<tr>
<th scope="col">AssetID</th>
<th scope="col">Loaction</th>
<th scope="col">AreaIn</th>
<th scope="col">Rooms</th>
<th scope="col">ImageURL</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody align="center">
#foreach (var a in #Model.OwnAssetsList)
{
String[] assetArray = new String[8] { a.AssetID.ToString(), a.OwnerID.ToString(), a.OwnerPublicKey.ToString(), a.Loaction.ToString(), a.AreaIn.ToString(), a.Rooms.ToString(), a.ImageURL.ToString(), a.Price.ToString() };
<tr>
<td>#a.AssetID</td>
<td>#a.Loaction</td>
<td>#a.AreaIn</td>
<td>#a.Rooms</td>
<td><a target="_blank" href=#a.ImageURL>Click</a></td>
<td><button class="btn btn-primary" data-toggle="modal" data-target="#exampleModalLong" onclick="offerContract(#a.Loaction/* or #a.ImageURL*/)">Offer Contract</button></td>
</tr>
}
</tbody>
In Javascript:
#section scripts
{
<script type="text/javascript">
function offerContract(param)
{
document.getElementById("dialogAssetID").innerHTML = "Asset No:".bold()+param.AssetID;
document.getElementById("dialogOwnerAddress").innerHTML="Your Public Key:" +param.OwnerID;
}
</script>
}
The javascript function fails if and only if I passing #a.Loaction or #a.ImageURL.
Here is the error in the console: 'Uncaught SyntaxError: missing ) after argument list'.
The rest properties of the model passed successfully.
The '#a.Loaction' and '#a.ImageURL' working fine in the HTML table
I am adding now the model and the table scheme:
public class Asset
{
[Key]
public int AssetID { get; set; }
[Required]
public int OwnerID { get; set; }
[Required]
public string OwnerPublicKey { get; set; }
[Required]
public string Loaction { get; set; }
[Required]
public int AreaIn { get; set; }
[Required]
public int Rooms { get; set; }
[Required]
public string ImageURL { get; set; }
[Required]
public double Price { get; set; }
}
I will appreciate any help. More than 6 hours spent on this issue.
in your Razor page, you basically need to pre-generate a javascript object that you will then pass along to your JS:
in your scripts section is a good place:
#section scripts {
<script type="text/javascript">
var data = #Json.Serialize(#Model.OwnAssetsList);
function offerContract(index)
{
document.getElementById("dialogAssetID").innerHTML = "Asset No:".bold() + data[index].assetId;
document.getElementById("dialogOwnerAddress").innerHTML="Your Public Key:" + data[index].ownerId;
}
</script>
Your Razor then could look something like this (note, since you are opting for foreach, there was no direct way to get current iteration index, so I had to introduce one myself):
#{var i = 0} //
#foreach (var a in #Model.OwnAssetsList)
{
<tr>
...
<td><button class="btn btn-primary" data-toggle="modal" data-target="#exampleModalLong" onclick="offerContract(#i)">Offer Contract</button></td>
</tr>
i += 1; // next iteration
}
}
UPD: if you absolutely must pass strings from Razor to JS, you will need to quote them:
<td><button class="btn btn-primary" data-toggle="modal" data-target="#exampleModalLong" onclick="offerContract('#a.Loaction')">Offer Contract</button></td>
I suggest single quotes so Razor does not get confused
I found another way to pass the problematic properties:
<tbody align="center">
#{ int i = 0;}
#foreach (var a in #Model.OwnAssetsList)
{
string loaction = "loc" + i;
string url = "url" + i;
<tr>
<td>#a.AssetID</td>
<td id=#loaction>#a.Loaction</td>
<td>#a.AreaIn</td>
<td>#a.Rooms</td>
<td><a id=#url target="_blank" href=#a.ImageURL>Click</a></td>
<td><button class="btn btn-primary" data-toggle="modal" data-target="#exampleModalLong" onclick="offerContract( #i)">Offer Contract</button></td>
</tr>
i++;
}
</tbody>
And in the function:
function offerContract(param)
{
var idLoac = "#loc" + param;
var idUrl = "#url" + param;
var demdloc = $(idLoac).text();
var demdurl = $(idUrl).attr("href");
document.getElementById("dialogAssetID").innerHTML = "Asset No:".bold() + demdloc;
document.getElementById("dialogOwnerID").innerHTML = "Your ID:".bold() + demdurl;
}
And the properties are perfectly passing.

How do you use the Datamuse API to get words, and then unpack the JSON response in Javascript?

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>

Update Connected Database Table as Rows are Added to an ASP.NET MVC 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.

how to pass list of object from view to controller on submit button using html.beginform [duplicate]

I have a HTML table as below in my View:
<table id="tblCurrentYear">
<tr>
<td>Leave Type</td>
<td>Leave Taken</td>
<td>Leave Balance</td>
<td>Leave Total</td>
</tr>
#foreach (var item in Model.LeaveDetailsList)
{
<tr>
<td>#Html.TextBoxFor(m => item.LeaveType, new { width = "100" })</td>
<td>#Html.TextBoxFor(m => item.LeaveTaken, new { width = "100" })</td>
<td>#Html.TextBoxFor(m => item.LeaveBalance, new { width = "100" })</td>
<td>#Html.TextBoxFor(m => item.LeaveTotal, new { width = "100" })</td>
</tr>
}
</table>
I want to iterate through all the html table rows and insert the values in ADO.NET DataTable.
Simple speaking, converting HTML Table to ADO.NET DataTable.
How to extract values from HTML Table and insert into ADO.NET DataTable?
The view is based on the following model
public class LeaveBalanceViewModel
{
public LeaveBalanceViewModel()
{
this.EmployeeDetail = new EmployeeDetails();
this.LeaveBalanceDetail = new LeaveBalanceDetails();
this.LeaveDetailsList = new List<LeaveBalanceDetails>();
}
public EmployeeDetails EmployeeDetail { get; set; }
public LeaveBalanceDetails LeaveBalanceDetail { get; set; }
public List<LeaveBalanceDetails> LeaveDetailsList { get; set; }
}
In order to bind to a model on post back, the name attributes of the form controls must match the model properties. Your use of a foreach loop does not generate the correct name attributes. If you inspect the html you will see multiple instances of
<input type="text" name="item.LeaveType" .../>
but in order to bind to your model the controls would need to be
<input type="text" name="LeaveDetailsList[0].LeaveType" .../>
<input type="text" name="LeaveDetailsList[1].LeaveType" .../>
etc. The easiest way to think about this is to consider how you would access the value of a LeaveType property in C# code
var model = new LeaveBalanceViewModel();
// add some LeaveBalanceDetails instances to the LeaveDetailsList property, then access a value
var leaveType = model.LeaveDetailsList[0].LeaveType;
Since your POST method will have a parameter name (say model), just drop the prefix (model) and that's how the name attribute of the control must be. In order to do that you must use either a for loop (the collection must implement IList<T>)
for(int i = 0; i < Model.LeaveDetailsList.Count; i++)
{
#Html.TextBoxFor(m => m.LeaveDetailsList[i].LeaveType)
....
}
or use a custom EditorTemplate (the collection need only implement IEnumerable<T>)
In /Views/Shared/EditorTemplates/LeaveBalanceDetails.cshtml
#model yourAssembly.LeaveBalanceDetails
<tr>
<td>#Html.TextBoxFor(m => m.LeaveType)</td>
....
</tr>
and then in the main view (not in a loop)
<table>
.... // add headings (preferably in a thead element
<tbody>
#Html.EditorFor(m => m.LeaveDetailsList)
</tbody>
</table>
and finally, in the controller
public ActionResult Edit(LeaveBalanceViewModel model)
{
// iterate over model.LeaveDetailsList and save the items
}
With respect to your requirement, try this
jQuery(document).on("change", ".DDLChoices", function (e) {
var comma_ChoiceIds = '';
var comma_ChoicesText = '';
$('input[class="DDLChoices"]').each(function (e) {
if (this.checked) {
comma_ChoiceIds = comma_ChoiceIds + $(this).val() + ',';
comma_ChoicesText = comma_ChoicesText + $(this).parent('label').parent() + ',';
}
});
$('#ChoiceIds').val(comma_ChoiceIds);
$('#ChoiceText').val(comma_ChoicesText);
});
#using (Html.BeginForm("Actionname", "Controllername", FormMethod.Post, new { id = "frmChoices" }))
{
#Html.HiddenFor(m => m.ChoiceText, new { #id = "ChoiceText" })
#Html.HiddenFor(m => m.ChoiceIds, new { #id = "ChoiceIds" })
<div class="form-group">
<div>
<table>
<tr>
<th>Name</th>
<th>Selected</th>
</tr>
#foreach (var item in #Model.Choices)
{
<tr>
<td> <label>#item.ChoicesText</label> </td>
<td> <input class="DDLChoices" value="#item.ChoiceIds" type="checkbox" /></td>
</tr>
}
</table>
</div>
<input type="button" value="Submit" onclick="return ChoicesPoster.passChoices()"
</div>
}

Send list of objects from SignalR hub to JavaScript method

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);
}

Categories