I have populated a table with info from my database, but I need another column where I can delete an entry out of the table and out of the database.
I've started to create a delete statement, but I don't know what I need to delete just a single entry.
Here's my code so far:
#{
var db = Database.Open("StayInFlorida");
var sPropertyId = Request.QueryString["PropertyID"];
var roominfo = "SELECT * FROM RoomInfo WHERE PropertyID=#0";
var qroominfo = db.Query(roominfo, sPropertyId);
var droominfo = "DELETE ??? FROM RoomInfo"
if (IsPost){
var deletesingleroom = db.Query(droominfo, sPropertyId);
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
<link href="~/css/bootstrap.css" rel="stylesheet">
</head>
<body>
<div id="tab2" class="tab-pane">
<h4>Room Information</h4>
<table class="table table-bordered">
<thead>
<tr>
<th>Room Title</th>
<th>Room Type</th>
<th>Room Description</th>
<th>Delete Room</th>
</tr>
</thead>
<tbody>
#foreach (var row in qroominfo)
{
<tr>
<td>#row.RoomTitle</td>
<td>#row.RoomType</td>
<td>#row.RoomDescription</td>
<td>
<form method="post">
<button type="submit" class="btn btn-success">Delete</button
</form>
</td>
</tr>
}
</tbody>
</table>
</div>
</body>
</html>
I think you have a problem with the delete statement in SQL in general, not particulary in Razor context.
The syntax for a delete statement is
DELETE FROM RoomInfo WHERE <some condition>
If you simply send this query :
DELETE FROM RoomInfo
This will delete all your rows.
So for deleting only one row from your POST result, it is kind of the same as the select :
DELETE FROM RoomInfo WHERE PropertyID=#0
Edit :
Now that you have a unique identifier that identifie the room you want to delete, you can update your code :
First, link the Id of your room to your delete button :
<form method="post">
<input type="text" name="id-room" value="#row.RoomID">
<button type="submit" class="btn btn-success">Delete</button
</form>
And when you submit the delete form, retrieve the room Id to delete :
var sRoomId = Request.QueryString["id-room"];
var droominfo = "DELETE FROM RoomInfo WHERE RoomId = " + sRoomId
Note that this code is terrible and will have a lot of security holes.
You are not supposed to access the database in a razor file for example. You are working like if you were in old fashioned PHP.
Try to inform yourself about ASP.NET MVC.
Related
I need to create view that contains table with pagination, sorting and search. I'm getting my data from backend api and then I'm passing it to the view.
My action method looks like this:
public async Task<IActionResult> Home(int page = 1)
{
var list = await _service.Get<List<Model.Rezervacija>>(page);
ViewBag.Page = page;
return View(list);
}
And I have this view:
#using eBiblioteka.Model
#model List<Rezervacija>
#{
ViewBag.Title = "Home";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div id="view-all">
#await Html.PartialAsync("_ViewAll", Model, null)
</div>
<a asp-action="Home" asp-route-page="#(ViewBag.Page - 1)">Previous</a>
<a asp-action="Home" asp-route-page="#(ViewBag.Page + 1)">Next</a>
And what view looks like:
And that all works. Don't pay attention for displaying pages number like this and changing with previous and next, I just wanted to simplify my question. So when i click next page, data changes and table also update very fast and that isn't problem.
But i see in tab that page is reloaded:
.
So is there any solution in asp .net core to do this without seeing that page reload. I need to call my action again to change this param "page" and then fetch new data from api without see that ugly page reload.
Thank you for all solutions.
So you want to create view that contains table with pagination, sorting and search without reloading.so you should use jquery for this.update your code like below:-
#using eBiblioteka.Model
#model IEnumerable<Rezervacija>
<div>
<table class="table table-striped border" id="myTable">
<thead>
<tr class="table-info">
<th>
#Html.DisplayNameFor(c => c.Name)
</th>
<th>
#Html.DisplayNameFor(c => c.SpecialTagId)
</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td> #item.Name </td>
<td> #item.SpecialTag.Name </td>
<td>
<partial name="_ButtonPartia3" model="#item.Id" /> //you can use partial view for delete or add data.
</td>
</tr>
}
</tbody>
</table>
</div>
<br /> <br />
#section scripts{
<script src="https://cdn.datatables.net/1.11.2/js/jquery.dataTables.min.js"></script>
<script type="text/javascript">
$(document).ready( function () {
$('#myTable').DataTable();
});
</script>
}
And Add this below link in your _Layout.cshtml:-
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.2/css/jquery.dataTables.min.css">
And your output will be like this:-
So when you will go from one page to another page, it will not reload because you used jquery. and it's already sorted and you can also search as needed.
You can use some excellent front-end frameworks. I now recommend you use layui, this is a Chinese community, of course you can also choose other ones. When this layui is paging, the URL is like the following format.
https://www.layui.com/demo/table/user/?page=2&limit=10
In this way, the .net core api can be called to perform partial refresh without reloading the entire page.
I have a View that lets users edit data that is fetched from a database and converted into a DataTable (for simplicity since the data can get really complicated and deep).
The issue is that when I POST the data back to the responsible Controller the controller receives the DataTable object but it's empty, e.g. the changes made by a user never get back to the Controller and cannot be saved to Database.
I am at most intermediate at web programming so I appreciate straight answers or direct pointers.
View:
#model System.Data.DataTable
#{
ViewData["Title"] = "Edit";
Layout = "~/Views/Shared/_LayoutAdminlte.cshtml";
}
#using (Html.BeginForm("EditSave", "Recipe", FormMethod.Post, new { #id = "Properties-Form" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<h2>#Html.DisplayFor(m => Model.TableName)</h2>
</div>
<div class="box box-primary">
<table id="Properties" class="table table-condensed">
<thead>
<tr>
#foreach (System.Data.DataColumn col in Model.Columns)
{
<th>
#Html.DisplayFor(m => col.Caption)
</th>
}
</tr>
</thead>
<tbody>
#foreach (System.Data.DataRow row in Model.Rows)
{
<tr>
#foreach (var cell in row.ItemArray)
{
<td>
#if (row.ItemArray.ToList().IndexOf(cell) == 0)
{
#cell.ToString()
}
else
{
<input asp-for="#cell" />
}
</td>
}
</tr>
}
</tbody>
</table>
</div>
<div class="box-footer">
<!-- id="Save" -->
<input class="btn btn-primary pull-right" type="submit" value="Spara" id="Save" />
<i class="fa fa-show"></i> Visa
<i class="fa fa-show"></i> Avbryt
</div>
</div>
}
#section Scripts{
#await Html.PartialAsync("_ValidationScriptsPartial")
}
Controller:
[HttpPost]
public ActionResult EditSave(DataTable model)
{
Debugger.Break();
return View("Edit", model);
}
This <input asp-for="#cell" /> is your problem.
If you run your program and use the developer tools to inspect the html generated for the input fields, you will notice the generated html attributes.
the particular one that you should pay attention to is the name attribute.
The way model binding works in .net core when you send data to the controller.
public IActionResult DoSomething(Model model) { ... }
you would have match the name attribute to the property of the object. Example:
<input name="model.Level" value="8999" />
so then you would get var level = model.Level and level will be 8999.
So you have to take care when you use the asp-for it's not doing as much heavy lifting as you think. Always check the html generated.
PS
Don't use DataTables, other developers will throw rocks at you. Don't be lazy map to an actual object or use an ORM, programs quickly become unmaintainable if you use them to dynamically store data.
Solution: Just added null default values to the HTML parameters. Seems to have solved it!
So I have an admin page (HTML) with two forms. First form is to add to an SQL database and has 4 input boxes, second form deletes from a SQL database and has 1 input box. If I use the first form, everything is OK. But if I leave the first form empty and just put a value for the 2nd form, I get an NumberFormatException for String = "" I can only assume because the first form is empty. I'm trying to have the user either fill the first form and leave the 2nd empty, or vice versa. Any advice on how to better approach this would be great.
This is my HTML page
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Admin</title>
<link rel="stylesheet" href="myStyle.css">
</head>
<body>
<h1>Welcome to the admin page.</h1>
<h2>Please enter the new product to be added:</h2>
<form action="eShop" method="Post">
<table class="tableBox">
<tr>
<td align="left"><b>Item Code:</b></td>
<td align="left"><input type="number" name="code"></td>
</tr>
<tr>
<td align="left"><b>Item Name:</b></td>
<td align="left"><input type="text" name="name"></td>
</tr>
<tr>
<td align="left"><b>Item Price:</b></td>
<td align="left"><input type="number" name="price"></td>
</tr>
<tr>
<td align="left"><b>Is Taxable:</b></td>
<td align="left"><input type="text" name="taxable"></td>
<tr>
<td align="center" colspan="2"><input type="submit" name="action" value="Update!"></td>
</tr>
</table>
</form>
<h2>Enter the code of the product you want to delete:</h2>
<form action="eShop" method="Post">
<table class="tableBox">
<tr>
<td align="left"><b>Item Code:</b></td>
<td align="left"><input type="number" name="code"></td>
</tr>
<tr>
<td align="center" colspan="2"><input type="submit" name="action" value="Delete!"></td>
</tr>
</table>
</form>
</body>
</html>
This is the section in my servlet that gets the parameters
else if(request.getParameter("action").equals("Delete!")) {
DataAccessImpl temp = new DataAccessImpl();
int code = Integer.parseInt(request.getParameter("code"));
temp.deleteItem(code);
}
This is the DataAccessImpl class used in the servlet, particularly the method that will delete the row.
public void deleteItem(int code) {
connect();
String deleteStm = ("DELETE FROM ProductCatalogue WHERE code = " + code);
PreparedStatement pstm = null;
System.out.println("Beginning to delete product from database...");
try {
pstm = conn.prepareStatement(deleteStm);
System.out.println("Delete complete!");
}
catch(SQLException e) {
e.printStackTrace();
}
}
in first form name your submit button like this:
<input type="submit" name="updateAction" value="Update!">
in second form name your submit button like this:
<input type="submit" name="deleteAction" value="Delete!">
Servlet Code should be like this:
else if(request.getParameter("deleteAction").equals("Delete!")) {
DataAccessImpl temp = new DataAccessImpl();
int code = Integer.parseInt(request.getParameter("code"));
temp.deleteItem(code);
}
I am looking for a way to add autocomplete data from my code to an "invoice" page automatically. I want the user to be able to also click to add or remove each item(quickbooks style, with multiple form fields available, and adding dynamically) and in the long run, be able to drag elements to a certain position in the invoice. All I am looking for now is this :
good : pseudocode on how to do this
best : basic working code to take off with.
This is what I have so far :
Page that calls the data :
<?php
require 'database.php';
require 'results.php';
if(!empty($_GET['wid'])) { $wid = $_GET['wid']; }
elseif(!empty($_POST['wid'])) { $wid = $_POST['wid']; }
else { $wid = null; }
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/bootstrap.min.js"></script>
<script src="js/jquery-1.9.1.min.js"></script>
<script src="js/engine.js"></script>
</head>
<body>
<div class="container-fluid">
<div class="span10 offset1">
<div class="row">
<h3>Add Item to Workorder</h3>
</div>
<form class="form-horizontal" action="additems.php" method="post">
<?php
// Add Custom Call for values from prior page ?>
<input type="hidden" name="wid" value="<?php echo htmlentities($wid); ?>">
<?php
//not required, but for get link purposes
if(isset($_POST['search']) && $_POST['search']!=''){
$search = $_POST['search'];
} elseif (isset($_GET['search']) && $_GET['search']!=''){
$search = $_GET['search'];
} else {
$search='';
}
//
echo"
<input type='text' class='search_input' name='search' id='search' placeholder='search' value='$search' autofocus>
<div id='search_output' class='search_output'>";
?>
Page that retrieves results :
<?php
require_once"database.php";//connection to database
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(isset($_POST['search']) && $_POST['search']){
$search=$_POST['search'];
} elseif(isset($_GET['search']) && $_GET['search']){
$search=$_GET['search'];
}
if(isset($search)){
$search = '%' . strtr($search, ['%' => '\%', '_' => '\_']);
$search = str_replace(" ", "%", $search);
$search= "%$search%";
$sql="select * from products where `model` LIKE ? OR `category` LIKE ? OR `description` LIKE ? OR `subcategory` LIKE ? LIMIT 50;";
$statement = $pdo->prepare($sql);
$statement->execute([$search, $search, $search, $search]);
//configure for your custom data dump to autocomplete
echo "
<table class='table table-striped table-bordered' width='100%'>
<thead>
<tr>
<th>Model</th>
<th>Category</th>
<th>Description</th>
</tr>
</thead>
<tbody>
";
while($row = $statement->fetch()){
$item=$row['model'];
$title=$row['category'];
$description=$row['description'];
echo "
<tr>
<td>
<a href='?item=$item'>
$item
</td><td>
$title
</td><td>
$description
</a>
</td>
</tr>
";
}
//
}
This code contains Javascript and AJAX code which is for making dynamic search from the input and displaying the sql results in the 'search_output'.
<input type='text' class='search_input' onkeyup="performSearch(this.value);" id='search' placeholder='search' value='$search' autofocus>
<div id='search_output' class='search_output'>";
<script>
function performSearch(data) {
if (data.length > 0) {
var xmlhttp = new XMLHttpRequest() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("search_output").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "YOURPHPFILENAME.php?search=" + data, true);
xmlhttp.send();
}
}
</script>
Unfortunately for other Dynamic features you will need to learn JQUERY/AJAX and understand HTML DOM. There may be Third party API which may do this.
I'm fairly new to html development and don't know how to tackle this problem. I need to create a table with some editable cells. Then I need to update a specific row in a database table based in the row edited. I've created some working solution that I'm almost sure don't use a correct approach to the problem, so I need to know how can I can I make this fine.
Note the repeated form. I would like to have only one form and one submit button to update only those edited rows.
#using Oracle.DataAccess.Client;
#using Oracle.DataAccess.Types;
#{
string some_conn = "SomeConnectionString";
OracleConnection conn = new OracleConnection(some_conn);
var comm = new OracleCommand("select * from some_table",conn);
conn.Open();
if(IsPost){
var some_id = Request.Form["some_id"];
var some_value = Request["some_value"];
var update_comm = new OracleCommand("update some_table"+
" set some_value ='"+some_value+"'" +
" where some_id ='" + some_id + "'", conn ) ;
update_comm.ExecuteNonQuery();
}
var dr = comm.ExecuteReader();
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<table>
#while(dr.Read()){
<tr>
#for(int i= 0; i < 7 ; i++){
if(i != 5){
<td> #(Convert.ToString(dr.GetValue(i)))</td>
}
}
<form method="post" action="">
<td> <input type="text" name="some_id" contenteditable="false" value="#(Convert.ToString(dr.GetValue(5)))"></td>
<td><textarea name="some_value" cols="10" rows="10">#(Convert.ToString(dr.GetValue(7)))</textarea></td>
<td> <input type="submit" value="update"></td>
</form>
</tr>
}
</table>
</body>
</html>
#{
conn.Close();
conn.Dispose();
}