Answered by:
Asp.net C# JQuery draggable item save position in sql database

Question
-
User1202507954 posted
Hallo everybody! Due to the corona virus my friends and me can not meet. So i try to create a little game on my website, where you can drag objects and other people see them on the last location even though the page is reloaded.
So basically i need to store the position in my sql db. I already read a lot of blog articles and stuff, but somehow it doesnt work for me. I think it is about passing the variables from AJAX to C# codebehind, but still i can not identify the mistake. it would be very nice if you can help me with this!
here is my code:
aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Prototyp.aspx.cs" Inherits="Login_Website_Neu.Prototyp" %> <!DOCTYPE html> <script src="Scripts/modernizr-2.8.3.js" type="text/javascript">></script> <script src="Scripts/jquery-ui.js" type="text/javascript">></script> <script src="Scripts/jquery-3.3.1.slim.min.js" type="text/javascript">></script> <script src="Scripts/jquery-3.3.1.slim.js" type="text/javascript">></script> <script src="Scripts/jquery-3.3.1.min.js" type="text/javascript">></script> <script src="Scripts/jquery-3.3.1.intellisense.js" type="text/javascript">></script> <script src="Scripts/jquery-ui-1.12.1.min.js" type="text/javascript">></script> <script src="Scripts/bootstrap.js" type="text/javascript">></script> <script type="text/javascript"> $(function() { $("#d1").draggable( { drag: function(event, ui) { $("#d1").css("opacity", "0.6"); // Semi-transparent when dragging }, stop: function (event, ui) { //nachricht($('#d1').attr('el')); saveCoords(ui.offset.left, ui.offset.top, $('#d1').attr('el')); $("#d1").css("opacity", "1.0"); // Full opacity when stopped }, cursor: "move" }); }); //function nachricht(x) { // alert(x) //} function saveCoords(x, y, el, userid) { $.ajax({ type: "POST", url: "Prototyp.aspx/Prototyp.aspx.cs/Prototyp/Coordinates/SaveCoords", data: "{x: '" + x + "', y: '" + y + "', element: '" + el + "', userid: '1'}", contentType: "application/json; charset=utf-8", dataType: "json", success: function(response) { if (response.d != '1') { alert('Not Saved!'); } }, error: function(response) { alert(response.responseText); } }); } </script> <body> <form id="form1" runat="server"> <div> <img src="Bilder/Mustard.png" alt="" id="d1" width="30" height="30" runat="server" /> </div> </form> </body>
and the aspx.cs:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI.WebControls; using System.Web.Services; using System.Web.Script.Services; using System.Data.SqlClient; using System.Data; using System.Web.UI.HtmlControls; using System.Configuration; using System.Web.UI; namespace Login_Website_Neu { public partial class Prototyp : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [ScriptService] public class Coordinates : WebService { [WebMethod] public int SaveCoords(int x, int y, string element, int userid) { string connect = "Server=VMD47703;Database=Benutzerdefinierte_Kader;Trusted_Connection=True;"; int result = 1; using (SqlConnection conn = new SqlConnection(connect)) { string query = "insert into [Benutzerdefinierte_Kader].[dbo].[Coords] values (@xPos, @yPos, @element, @userid)"; using (SqlCommand cmd = new SqlCommand(query, conn)) { cmd.Parameters.AddWithValue("xPos", x); cmd.Parameters.AddWithValue("yPos", y); cmd.Parameters.AddWithValue("element", element); cmd.Parameters.AddWithValue("userid", userid); conn.Open(); result = (int)cmd.ExecuteNonQuery(); } } return result; } [WebMethod] public DataTable GetSavedCoords(int userid) { DataTable dt = new DataTable(); string connect = "Data Source=VMD47703;Integrated Security=True"; using (SqlConnection conn = new SqlConnection(connect)) { string query = "SELECT xPos, yPos, Element FROM [Benutzerdefinierte_Kader].[dbo].[Coords] WHERE UserID = @UserID"; using (SqlCommand cmd = new SqlCommand(query, conn)) { cmd.Parameters.AddWithValue("UserID", userid); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(dt); return dt; } } } public partial class PersistDraggable : Page { protected void Page_Load(object sender, EventArgs e) { Coordinates coords = new Coordinates(); DataTable dt = coords.GetSavedCoords(1); foreach (DataRow row in dt.Rows) { HtmlControl ctl = (HtmlControl)this.FindControl(row["element"].ToString()); if (ctl != null) { ctl.Style.Add("left", row["xPos"].ToString() + "px"); ctl.Style.Add("top", row["yPos"].ToString() + "px"); } } } } } } }
thank you guys! and stay healthy!
Thursday, March 26, 2020 6:05 PM
Answers
-
User-1330468790 posted
Hi Schlumpinator,
Firstly, we need to confirm if we want to achieve the same target.
1.After you drag and drop the image, the position of the image will be stored in the db. The method we want to take is ajax post + WebMethod.
2.If you or other people load the page and people will see that the image is located in the last position.
3.We take user id as '1' to simplify the scenario.
Then, I need to point out few mistakes you made which might be helpful for your following development.
1.In your code, you wrong used the web method as the attribute should be added on the method which is static.
2.If you call the web method through ajax, you'd better directly use the url for the web method instead of nested url which possibly is incorrect.
3.If you are willing to make the picture rendered in the same position, you should take the coords from the same position field. However, what I can see is that you take position x and y coordinates from offset and add the x and y coordinates to position property of Css style.
PS: Here I takes the "id" as the identifier of the element so that the page can capture it and assign the value to its position style.
More details, you could refer to below code and focus on the content in yellow background:
.aspx page: Script + HTML
<script type="text/javascript"> $(function () { $("#d1").draggable( { drag: function (event, ui) { $("#d1").css("opacity", "0.6"); // Semi-transparent when dragging }, stop: function (event, ui) { saveCoords(ui.position.left, ui.position.top, $('#d1').attr('id')); $("#d1").css("opacity", "1.0"); // Full opacity when stopped }, cursor: "move" }); }); function saveCoords(x, y, el, userid) { $.ajax({ type: "POST", url: "DraggableAndSaveCoords.aspx/SaveCoords", data: "{x: '" + x + "', y: '" + y + "', element: '" + el + "', userid: '1'}", contentType: "application/json; charset=utf-8", dataType: "json", success: function (response) {
// if '1', it means that the insert is successful. console.log(response); }, error: function (response) { alert(response.responseText); } }); } </script> </head> <body> <form id="form1" runat="server"> <div> <img src="Images/personbg.png" alt="" id="d1" width="30" height="30" runat="server" /> </div> </form> </body>Code behind:
protected void Page_Load(object sender, EventArgs e) { SetCoordsForElement(); } [WebMethod] public static int SaveCoords(int x, int y, string element, int userid) { string sql = "INSERT INTO [Coords] VALUES (@xPos, @yPos, @element, @userid)"; SqlParameter[] parameters = { new SqlParameter("@xPos", x), new SqlParameter("@yPos",y), new SqlParameter("@element", element), new SqlParameter("@userid", userid) }; return ExecuteNonQuery(sql, parameters); } public void SetCoordsForElement() { string sql = "SELECT TOP 1 xPos, yPos, Element FROM [Coords] WHERE UserID = @UserID ORDER BY ID DESC"; SqlParameter[] parameters = { new SqlParameter("@UserID", 1) }; DataTable dt = SelectFromDatabase(sql, parameters); foreach(DataRow row in dt.Rows) { HtmlControl ctl = (HtmlControl)this.FindControl(row["Element"].ToString()); if(ctl != null) { ctl.Style.Add("left", row["xPos"].ToString() + "px"); ctl.Style.Add("top", row["yPos"].ToString() + "px"); } } } public static DataTable SelectFromDatabase(string sql, SqlParameter[] parameters) { string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; using (SqlConnection con = new SqlConnection(constr)) { using (SqlCommand cmd = new SqlCommand(sql, con)) { if (parameters != null) { cmd.Parameters.AddRange(parameters); } using (SqlDataAdapter sda = new SqlDataAdapter(cmd)) { DataTable dt = new DataTable(); sda.Fill(dt); return dt; } } } } public static int ExecuteNonQuery(string sql, SqlParameter[] parameters) { // -1 means the query is not successful int result = -1; string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; using (SqlConnection conn = new SqlConnection(constr)) { try { conn.Open(); using (SqlCommand cmd = new SqlCommand(sql, conn)) { if (null != parameters) { cmd.Parameters.AddRange(parameters); } result = cmd.ExecuteNonQuery(); } } catch (SqlException ex) { Debug.WriteLine(ex.ToString()); } finally { conn.Close(); } } return result; }
Demo: I refresh the page to demonstrate that the position is saved in database and recovered after the page loaded.
Hope this can help you.
Best regards,
Sean
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Friday, March 27, 2020 6:56 AM -
User475983607 posted
Saving the current position does not work for some reason.What is "not working"?
Have you tried setting a break point and single stepping through your code?
https://docs.microsoft.com/en-us/visualstudio/debugger/debugger-feature-tour?view=vs-2019
Are break points in the Web Method getting hit? Your catch block writes to the console. Are you checking the output for errors? What value is returned to the AJAX function? You need to open the browser's dev tools to see the response. Are you using the browser's dev tools?
https://developers.google.com/web/tools/chrome-devtools/console
Take a few minutes to figure out where your code is not working as expected.
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Friday, March 27, 2020 12:08 PM
All replies
-
User-1330468790 posted
Hi Schlumpinator,
Firstly, we need to confirm if we want to achieve the same target.
1.After you drag and drop the image, the position of the image will be stored in the db. The method we want to take is ajax post + WebMethod.
2.If you or other people load the page and people will see that the image is located in the last position.
3.We take user id as '1' to simplify the scenario.
Then, I need to point out few mistakes you made which might be helpful for your following development.
1.In your code, you wrong used the web method as the attribute should be added on the method which is static.
2.If you call the web method through ajax, you'd better directly use the url for the web method instead of nested url which possibly is incorrect.
3.If you are willing to make the picture rendered in the same position, you should take the coords from the same position field. However, what I can see is that you take position x and y coordinates from offset and add the x and y coordinates to position property of Css style.
PS: Here I takes the "id" as the identifier of the element so that the page can capture it and assign the value to its position style.
More details, you could refer to below code and focus on the content in yellow background:
.aspx page: Script + HTML
<script type="text/javascript"> $(function () { $("#d1").draggable( { drag: function (event, ui) { $("#d1").css("opacity", "0.6"); // Semi-transparent when dragging }, stop: function (event, ui) { saveCoords(ui.position.left, ui.position.top, $('#d1').attr('id')); $("#d1").css("opacity", "1.0"); // Full opacity when stopped }, cursor: "move" }); }); function saveCoords(x, y, el, userid) { $.ajax({ type: "POST", url: "DraggableAndSaveCoords.aspx/SaveCoords", data: "{x: '" + x + "', y: '" + y + "', element: '" + el + "', userid: '1'}", contentType: "application/json; charset=utf-8", dataType: "json", success: function (response) {
// if '1', it means that the insert is successful. console.log(response); }, error: function (response) { alert(response.responseText); } }); } </script> </head> <body> <form id="form1" runat="server"> <div> <img src="Images/personbg.png" alt="" id="d1" width="30" height="30" runat="server" /> </div> </form> </body>Code behind:
protected void Page_Load(object sender, EventArgs e) { SetCoordsForElement(); } [WebMethod] public static int SaveCoords(int x, int y, string element, int userid) { string sql = "INSERT INTO [Coords] VALUES (@xPos, @yPos, @element, @userid)"; SqlParameter[] parameters = { new SqlParameter("@xPos", x), new SqlParameter("@yPos",y), new SqlParameter("@element", element), new SqlParameter("@userid", userid) }; return ExecuteNonQuery(sql, parameters); } public void SetCoordsForElement() { string sql = "SELECT TOP 1 xPos, yPos, Element FROM [Coords] WHERE UserID = @UserID ORDER BY ID DESC"; SqlParameter[] parameters = { new SqlParameter("@UserID", 1) }; DataTable dt = SelectFromDatabase(sql, parameters); foreach(DataRow row in dt.Rows) { HtmlControl ctl = (HtmlControl)this.FindControl(row["Element"].ToString()); if(ctl != null) { ctl.Style.Add("left", row["xPos"].ToString() + "px"); ctl.Style.Add("top", row["yPos"].ToString() + "px"); } } } public static DataTable SelectFromDatabase(string sql, SqlParameter[] parameters) { string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; using (SqlConnection con = new SqlConnection(constr)) { using (SqlCommand cmd = new SqlCommand(sql, con)) { if (parameters != null) { cmd.Parameters.AddRange(parameters); } using (SqlDataAdapter sda = new SqlDataAdapter(cmd)) { DataTable dt = new DataTable(); sda.Fill(dt); return dt; } } } } public static int ExecuteNonQuery(string sql, SqlParameter[] parameters) { // -1 means the query is not successful int result = -1; string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; using (SqlConnection conn = new SqlConnection(constr)) { try { conn.Open(); using (SqlCommand cmd = new SqlCommand(sql, conn)) { if (null != parameters) { cmd.Parameters.AddRange(parameters); } result = cmd.ExecuteNonQuery(); } } catch (SqlException ex) { Debug.WriteLine(ex.ToString()); } finally { conn.Close(); } } return result; }
Demo: I refresh the page to demonstrate that the position is saved in database and recovered after the page loaded.
Hope this can help you.
Best regards,
Sean
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Friday, March 27, 2020 6:56 AM -
User1202507954 posted
Hey Sean,
thank you a lot for this awesome reply to my post. You help me so much on fixing and understanding the problem! I am pretty new to this topic and im very motivated to learn more and more.
Taking your advices now the application loads a position, if i put the values directly into the database. Saving the current position does not work for some reason.
1.After you drag and drop the image, the position of the image will be stored in the db. The method we want to take is ajax post + WebMethod.
2.If you or other people load the page and people will see that the image is located in the last position.
3.We take user id as '1' to simplify the scenario.
Yes! That is exactly what i want to achieve. :-)
1.In your code, you wrong used the web method as the attribute should be added on the method which is static.
2.If you call the web method through ajax, you'd better directly use the url for the web method instead of nested url which possibly is incorrect.
3.If you are willing to make the picture rendered in the same position, you should take the coords from the same position field. However, what I can see is that you take position x and y coordinates from offset and add the x and y coordinates to position property of Css style.
I tried to take your advices and fix my problem. I think #2 is still incorrect in my code. I will post my code below, it would be very nice if you could again take a few minutes and point it out more cleary. As i already said, im pretty new to all this and so it is not easy to understand what exactly is the problem. still i give my best to follow you!
Prototyp.aspx:
<script type="text/javascript"> $(function () { $("#d1").draggable( { drag: function (event, ui) { $("#d1").css("opacity", "0.6"); // Semi-transparent when dragging }, stop: function (event, ui) { saveCoords(ui.position.left, ui.position.top, $('#d1').attr('id')); $("#d1").css("opacity", "1.0"); // Full opacity when stopped }, cursor: "move" }); }); function saveCoords(x, y, el, userid) { $.ajax({ type: "POST", url: "Prototyp.aspx/SaveCoords", data: "{x: '" + x + "', y: '" + y + "', element: '" + el + "', userid: '1'}", contentType: "application/json; charset=utf-8", dataType: "json", success: function (response) { // if '1', it means that the insert is successful. console.log(response); }, error: function (response) { alert(response.responseText); } }); } </script> <body> <form id="form1" runat="server"> <div> <img src="Bilder/Mustard.png" alt="" id="d1" width="30" height="30" runat="server" /> </div> </form> </body>
and prototyp.aspx.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI.WebControls; using System.Web.Services; using System.Web.Script.Services; using System.Data.SqlClient; using System.Data; using System.Web.UI.HtmlControls; using System.Configuration; using System.Web.UI; using System.Diagnostics; namespace Login_Website_Neu { public partial class Prototyp : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { SetCoordsForElement(); } [WebMethod] public static int SaveCoords(int x, int y, string element, int userid) { string sql = "INSERT INTO [Benutzerdefinierte_Kader].[dbo].[Coords] VALUES (@xPos, @yPos, @element, @userid)"; SqlParameter[] parameters = { new SqlParameter("@xPos", x), new SqlParameter("@yPos",y), new SqlParameter("@element", element), new SqlParameter("@userid", userid) }; return ExecuteNonQuery(sql, parameters); } public void SetCoordsForElement() { string sql = "SELECT TOP 1 xPos, yPos, Element FROM [Benutzerdefinierte_Kader].[dbo].[Coords] WHERE UserID = @UserID ORDER BY UserID DESC"; SqlParameter[] parameters = { new SqlParameter("@UserID", 1) }; DataTable dt = SelectFromDatabase(sql, parameters); foreach (DataRow row in dt.Rows) { HtmlControl ctl = (HtmlControl)this.FindControl(row["Element"].ToString()); if (ctl != null) { ctl.Style.Add("left", row["xPos"].ToString() + "px"); ctl.Style.Add("top", row["yPos"].ToString() + "px"); } } } public static DataTable SelectFromDatabase(string sql, SqlParameter[] parameters) { string constr = ConfigurationManager.ConnectionStrings["DarfAlles"].ConnectionString; using (SqlConnection con = new SqlConnection(constr)) { using (SqlCommand cmd = new SqlCommand(sql, con)) { if (parameters != null) { cmd.Parameters.AddRange(parameters); } using (SqlDataAdapter sda = new SqlDataAdapter(cmd)) { DataTable dt = new DataTable(); sda.Fill(dt); return dt; } } } } public static int ExecuteNonQuery(string sql, SqlParameter[] parameters) { // -1 means the query is not successful int result = -1; string constr = ConfigurationManager.ConnectionStrings["DarfAlles"].ConnectionString; using (SqlConnection conn = new SqlConnection(constr)) { try { conn.Open(); using (SqlCommand cmd = new SqlCommand(sql, conn)) { if (null != parameters) { cmd.Parameters.AddRange(parameters); } result = cmd.ExecuteNonQuery(); } } catch (SqlException ex) { Debug.WriteLine(ex.ToString()); } finally { conn.Close(); } } return result; } } }
Thank you!
Best regards,
Simon
Friday, March 27, 2020 11:16 AM -
User475983607 posted
Saving the current position does not work for some reason.What is "not working"?
Have you tried setting a break point and single stepping through your code?
https://docs.microsoft.com/en-us/visualstudio/debugger/debugger-feature-tour?view=vs-2019
Are break points in the Web Method getting hit? Your catch block writes to the console. Are you checking the output for errors? What value is returned to the AJAX function? You need to open the browser's dev tools to see the response. Are you using the browser's dev tools?
https://developers.google.com/web/tools/chrome-devtools/console
Take a few minutes to figure out where your code is not working as expected.
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Friday, March 27, 2020 12:08 PM -
User1202507954 posted
Hello mgebhard! Thank you for your answer!
It's working now. If you never used breakpoints, developer console etc. you dont know about it! So your post made me use that stuff and i found out that i get an error called
Object { Message: "Authentication failed.", StackTrace: null, ExceptionType: "System.InvalidOperationException" }
i made change by commenting out that line in the route_config
//settings.AutoRedirectMode = RedirectMode.Permanent;
now everything is working fine! Thank you guys!
Friday, March 27, 2020 12:38 PM -
User475983607 posted
It's working now. If you never used breakpoints, developer console etc. you dont know about it! So your post made me use that stuff and i found out that i get an error calledGlad you figured it out. Debugging and troubleshooting is a common developer task. It's a good idea to learn how to use the debugging tools.
IMHO, many of the questions on these forum can be solved quickly by setting a break point and finding where the code stops working as expected.
Friday, March 27, 2020 12:46 PM -
User1202507954 posted
mgebhard
Glad you figured it out. Debugging and troubleshooting is a common developer task. It's a good idea to learn how to use the debugging tools.
IMHO, many of the questions on these forum can be solved quickly by setting a break point and finding where the code stops working as expected.
Yes! Still many people use forums as debuggers :-)
Now i try to add a second image as a draggable object. Can you give me a hint, how to do this? Where in the code should i focus on?
Edit: Done! This forum is awesome!
Friday, March 27, 2020 1:26 PM -
User1202507954 posted
After working on that project im again stuck with positioning the draggable items on a game board. i use the img "Spielbrett" as a gameboard and i want to position the draggable imgs (d1.d2.d3.d4) on it. every user should see them on the same position.
i thought i have to do it with bootstrap, and now take the offset position of the element. if you see the code, i tried this at #d1. i have to round the offset, because all further variables are int.
can you please give me a hint, where to work on?
<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Trinkspiel2.aspx.cs" Inherits="Login_Website_Neu.Trinkspiel2" %> <asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server"> <!DOCTYPE html> <script src="Scripts/modernizr-2.8.3.js" type="text/javascript">></script> <script src="Scripts/jquery-ui.js" type="text/javascript">></script> <script src="Scripts/jquery-3.3.1.slim.min.js" type="text/javascript">></script> <script src="Scripts/jquery-3.3.1.slim.js" type="text/javascript">></script> <script src="Scripts/jquery-3.3.1.min.js" type="text/javascript">></script> <script src="Scripts/jquery-3.3.1.intellisense.js" type="text/javascript">></script> <script src="Scripts/jquery-ui-1.12.1.min.js" type="text/javascript">></script> <script src="Scripts/bootstrap.js" type="text/javascript">></script> <script type="text/javascript"> $(function () { $("#d1").draggable( { drag: function (event, ui) { $("#d1").css("opacity", "0.6"); // Semi-transparent when dragging }, stop: function (event, ui) { saveCoords(Math.round(ui.offset.left), Math.round(ui.offset.top), $('#d1').attr('id')); // here i try to use the offset for a test $("#d1").css("opacity", "1.0"); // Full opacity when stopped }, cursor: "move" }); $("#d2").draggable( { drag: function (event, ui) { $("#d2").css("opacity", "0.6"); // Semi-transparent when dragging }, stop: function (event, ui) { saveCoords(ui.position.left, ui.position.top, $('#d2').attr('id')); $("#d2").css("opacity", "1.0"); // Full opacity when stopped }, cursor: "move" }); $("#d3").draggable( { drag: function (event, ui) { $("#d3").css("opacity", "0.6"); // Semi-transparent when dragging }, stop: function (event, ui) { saveCoords(ui.position.left, ui.position.top, $('#d3').attr('id')); $("#d3").css("opacity", "1.0"); // Full opacity when stopped }, cursor: "move" }); $("#d4").draggable( { drag: function (event, ui) { $("#d4").css("opacity", "0.6"); // Semi-transparent when dragging }, stop: function (event, ui) { saveCoords(ui.position.left, ui.position.top, $('#d4').attr('id')); $("#d4").css("opacity", "1.0"); // Full opacity when stopped }, cursor: "move" }); }); function saveCoords(x, y, el, userid) { $.ajax({ type: "POST", url: "Trinkspiel2.aspx/SaveCoords", data: "{x: '" + x + "', y: '" + y + "', element: '" + el + "', userid: '1'}", contentType: "application/json; charset=utf-8", dataType: "json", success: function (response) { // if '1', it means that the insert is successful. console.log(response); }, error: function (response) { alert(response.responseText); } }); } </script> <div class="jumbotron"> <h1>Hallo Jungs</h1> <p class="lead">Hier gibts das Trinkspiel</p> </div> <div class="row"> <div class="col-md-10"> <div id="hintergrundbild"> <p><img id="Spielbrett" src="Bilder/Trinkspiel.jpg" width="100%"> </p> </div> </div> <div class="col-md-2"> <p><img id="d1" src="Bilder/Mustard.png" width="30" height="30" > </p> <p><img id="d2" src="Bilder/Mustard.png" width="30" height="30" > </p> <p><img id="d3" src="Bilder/Mustard.png" width="30" height="30" > </p> <p><img id="d4" src="Bilder/Mustard.png" width="30" height="30" > </p> </div> </div> <style> </style>
</asp:Content>and code behind:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI.WebControls; using System.Web.Services; using System.Web.Script.Services; using System.Data.SqlClient; using System.Data; using System.Web.UI.HtmlControls; using System.Configuration; using System.Web.UI; using System.Diagnostics; namespace Login_Website_Neu { public partial class Trinkspiel2 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { SetCoordsForElement(); } [WebMethod] public static int SaveCoords(int x, int y, string element, int userid) { string sql = "UPDATE [Benutzerdefinierte_Kader].[dbo].[Coords_] SET xPos = @xPos, yPos = @yPos WHERE element = @Element AND UserID = @UserID"; SqlParameter[] parameters = { new SqlParameter("@xPos", x), new SqlParameter("@yPos",y), new SqlParameter("@element", element), new SqlParameter("@userid", userid) }; return ExecuteNonQuery(sql, parameters); } public void SetCoordsForElement() { string sql = "SELECT xPos, yPos, Element FROM [Benutzerdefinierte_Kader].[dbo].[Coords_] WHERE UserID = @UserID ORDER BY UserID DESC"; SqlParameter[] parameters = { new SqlParameter("@UserID", 1) }; DataTable dt = SelectFromDatabase(sql, parameters); foreach (DataRow row in dt.Rows) { HtmlControl ctl = (HtmlControl)this.FindControl(row["Element"].ToString()); if (ctl != null) { ctl.Style.Add("left", row["xPos"].ToString() + "px"); ctl.Style.Add("top", row["yPos"].ToString() + "px"); } } } public static DataTable SelectFromDatabase(string sql, SqlParameter[] parameters) { string constr = ConfigurationManager.ConnectionStrings["DarfAlles"].ConnectionString; using (SqlConnection con = new SqlConnection(constr)) { using (SqlCommand cmd = new SqlCommand(sql, con)) { if (parameters != null) { cmd.Parameters.AddRange(parameters); } using (SqlDataAdapter sda = new SqlDataAdapter(cmd)) { DataTable dt = new DataTable(); sda.Fill(dt); return dt; } } } } public static int ExecuteNonQuery(string sql, SqlParameter[] parameters) { // -1 means the query is not successful int result = -1; string constr = ConfigurationManager.ConnectionStrings["DarfAlles"].ConnectionString; using (SqlConnection conn = new SqlConnection(constr)) { try { conn.Open(); using (SqlCommand cmd = new SqlCommand(sql, conn)) { if (null != parameters) { cmd.Parameters.AddRange(parameters); } result = cmd.ExecuteNonQuery(); } } catch (SqlException ex) { Debug.WriteLine(ex.ToString()); } finally { conn.Close(); } } return result; } } }
best regards,
simon
Friday, March 27, 2020 4:36 PM