How do you get data and bind to a table? - asp.net-core

I am trying to get data from a database and just bind the output to a table. I am using AJAX because some of my other codes won't allow me to mix with the IEnumerable. It doesn't seem to run the command and never trips breakpoints... Not sure what I might be doing wrong. I have scoured the internet and can't seem to find a solution or anything close, just broken code. It is loading the JS and even if I reference JS it still has the same behavior...
Index
#model Rabbit.Application.Models.Onboarding.Client
#{
ViewBag.Title = "Index";
Layout = "~/Areas/Onboarding/Views/Shared/_Layout.cshtml";
}
<h2> Clients</h2>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal" onclick="OpenAddPopup();">Add New Client</button><br /><br />
<fieldset>
<table table id="tblClient" class="table">
<thead>
<tr>
<th>companyName</th>
<th>PhoneNo</th>
<th>ContactPerson</th>
<th>Email</th>
<th>Address</th>
<th></th>
</tr>
</thead>
<tbody class="tbody">
</tbody>
</table>
</fieldset>
<script type="text/javascript">
//Load Data in Table when documents is ready
$(document).ready(function () {
$.ajax({
url: "/Clients/GetAllClients",
type: "GET",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result)
{
console.log(data);
if (result) {
//itetrate thorugh each record and bind it to td
var html = '';
$.each(result, function (key, item) {
html += '<tr>';
html += + '<td>' + item.companyName + '</td>'
html += + '<td>' + item.PhoneNo + '</td>'
html += + '<td>' + item.ContactPerson + '</td>'
html += + '<td>' + item.Email + '</td>'
html += + '<td>' + item.Address + '</td>'
html += +'</tr>';
});
$('#tbody').html(html);
},
error: function (errormessage) {
alert(errormessage.responseText);
}
});
}
</script>
Controller
public IActionResult Index()
{
return View();
}
public JsonResult GetAllClients()
{
var clientlist = (from client in _context.Client
select client).ToList();
return Json(clientlist);
}

After I tested it, it seems that this is just your grammar problem.
First,if you don't have a data variable,you need to delete console.log(data);.
Second,you should change html += + '<td>' + item.companyName + '</td>' to html += '<td>' + item.companyName + '</td>'.The same is true for the following, remove the + behind the =.
Third,you should change $('#tbody').html(html); to $('.tbody').html(html);,because you are using class="tbody".And you need to add a } after this,and add ) after the last one }.Because overall you are missing a } and a ).
Fourth,if $(document) reports an error, you can add <script src="https://code.jquery.com/jquery-1.12.4.js" type="text/javascript"></script> before <script type="text/javascript">.
Below is my test code,it works fine:
#model BindTable.Models.Client
<h2> Clients</h2>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal" onclick="OpenAddPopup();">Add New Client</button><br /><br />
<fieldset>
<table table id="tblClient" class="table">
<thead>
<tr>
<th>companyName</th>
<th>PhoneNo</th>
<th>ContactPerson</th>
<th>Email</th>
<th>Address</th>
<th></th>
</tr>
</thead>
<tbody class="tbody">
</tbody>
</table>
</fieldset>
<script src="https://code.jquery.com/jquery-1.12.4.js" type="text/javascript"></script>
<script type="text/javascript">
//Load Data in Table when documents is ready
$(document).ready(function () {
$.ajax({
url: "/Client/GetAllClients",
type: "GET",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result)
{
if (result) {
//itetrate thorugh each record and bind it to td
var html = '';
$.each(result, function (key, item) {
html += '<tr>';
html += '<td>' + item.companyName + '</td>'
html += '<td>' + item.phoneNo + '</td>'
html += '<td>' + item.contactPerson + '</td>'
html += '<td>' + item.email + '</td>'
html += '<td>' + item.address + '</td>'
html += '</tr>';
});
$('.tbody').html(html);
}
},
error: function (errormessage) {
alert(errormessage.responseText);
}
});
})
</script>
Test Result:

Related

Increase Prices 10 percent by ajax in asp.net core

I have some prices in my web site(asp.net core) .I wanna to add 10 percent to all of them by click a button and change all of them just by click a button .I wrote a service to add 10 percent to each price and there is a controller and in view I have a button . but it does not work.How should Icorrect it?
this is my code .
public interface IUpdatePricesService
{
ResultDto Execute(RequestUpdatePricesDto request);
}
public class UpdatePricesService : IUpdatePricesService
{
private readonly IDataBaseContext _context;
public UpdatePricesService(IDataBaseContext context)
{
_context = context;
}
public ResultDto Execute(RequestUpdatePricesDto request)
{
List<UpdatePrices> updatePrices = new List<UpdatePrices>();
UpdatePrices prices = new UpdatePrices();
foreach (var item in request.prices)
{
int p = Convert.ToInt32(prices);
p = p / 10;
p = p + p;
item.Price=p;
updatePrices.Add(prices);
};
_context.SaveChanges();
return new ResultDto
{
IsSuccess = true,
Message = "Updated",
};
}
}
private readonly IUpdatePricesService _updatePrices;
[HttpPost]
public IActionResult UpdatePricesInProduct()
{
var result = _updatePrices.Execute(new RequestUpdatePricesDto { });
return Json(result);
}
<div class="col-xl-12 col-lg-12 col-md-12 mb-1">
<fieldset class="form-group">
<br />
<a id="btnIncrease" class="btn btn-success col-md-12"> افزودن </a>
</fieldset>
</div>
<script>
$(document).ready(function () {
$('#btnIncrease').click(function () {
$.ajax({
contentType: 'application/x-www-form-urlencoded',
dataType: 'json',
url: "UpdatePricesInProduct",
type: "POST",
data: postData,
cache: false,
async: true,
success: function (data) {
alert(data);
}
});
})
</script>
Updated Answer As Per Comment:
"In Ajax the UpatePriceByAjax controller , do not works"
It shouldn't work the way you have written that. Because your ajax request is not in correct format.
"Ajax error explanation"
If you debug your code on browser you should get either of following
error at the begining. You have written Jquery like this way
<script> </script> which generating either of following error.
Additionally, your jquery has not ended correctly you have missed or
have not posted accordingly }); end braces are missing.
How to resolve that error
You should write your script using following way: So that there will be no error at the begining.
#section scripts {
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script>
$(document).ready(function () {
alert("Click");// Write your code here
});
</script>
}
"Another error you may get in Ajax"
data: postdata you haven't define what you are posting. I think for this price update request you don't need to post/submit any data as this method UpdatePricesInProduct does need anything as per your code.
"Finally Valid Ajax Request You should Write"
<div class="col-xl-12 col-lg-12 col-md-12 mb-1">
<fieldset class="form-group">
<br />
<a id="btnIncrease" class="btn btn-success col-md-12"> افزودن </a>
</fieldset>
</div>
#section scripts {
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script>
$(document).ready(function () {
$('#btnIncrease').click(function () {
alert("btnIncrease");
$.ajax({
contenttype: 'application/x-www-form-urlencoded',
datatype: 'json',
url: "updatepricesinproduct",
type: "post",
// data: postdata,
cache: false,
async: true,
success: function (data) {
alert(data);
}
});
});
});
</script>
}
"Output:"
Note: You should have above changes to get rid of your problem and make it
workable as expected.
Previous Answer And Working Sample:
Let say I have price list in my web site like below:
If now if you would like to update all price in the list together with
just a single button click then you could follow below steps:
HTML/Ajax:
<div class="col-xl-12 col-lg-12 col-md-12 mb-1">
<fieldset class="form-group">
<br />
<a id="btnIncrease" class="btn btn-success col-md-12"> افزودن Update Price </a>
</fieldset>
</div>
Javascript/Ajax:
#section scripts {
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script>
$(document).ready(function () {
$("#btnIncrease").click(function (e) {
alert("Fired!");
$.ajax("https://localhost:44361/UserLog/UpatePriceByAjax", {
method: "POST",
dataType: "json",
contentType: "application/json",
success: function (data) {
console.log(data);
}
});
alert("Successfully Updated");
location.reload(true);
});
});
</script>
}
C# Asp.net Core Controller
[HttpPost]
public ActionResult UpatePriceByAjax()
{
decimal incrementPercentage = 10;
List<PriceUpdateTable> ExistingPriceList = _context.priceUpdateTable.ToList();
foreach (var item in ExistingPriceList)
{
var updatedPricePercentage = item.Price * incrementPercentage / 100;
item.UpdatedPrice = item.Price + updatedPricePercentage;
_context.Update(item);
}
_context.SaveChanges();
return RedirectToAction("GetUpdatedPrice");
}
C# Asp.net View
#model IEnumerable<MVCApps.Models.PriceUpdateTable>
#{
ViewData["Title"] = "GetUpdatedPrice";
}
<h2>Get Updated Price</h2>
<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.ItemName)
</th>
<th>
#Html.DisplayNameFor(model => model.Price)
</th>
<th>
#Html.DisplayNameFor(model => model.UpdatedPrice)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.ItemName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Price)
</td>
<td>
#Html.DisplayFor(modelItem => item.UpdatedPrice)
</td>
<td>
<a asp-action="Edit" asp-route-id="#item.ItemId">Edit</a> |
<a asp-action="Details" asp-route-id="#item.ItemId">Details</a> |
<a asp-action="Delete" asp-route-id="#item.ItemId">Delete</a>
</td>
</tr>
}
</tbody>
</table>
C# Asp.net Controller For Above View
public async Task<IActionResult> GetUpdatedPrice()
{
var updatedPrice = await _context.priceUpdateTable.ToListAsync();
return View(updatedPrice);
}
Output
Note: This is scenario for you. Howevery, you can get the idea how you could implement that. Just modify the example as per your requirement.
Hope avobe steps guided you accordingly. If you encounter further concern feel free to share us.

My colorbox slideshow is not working properly

I want that when I click on view_attachments anchor then colorbox should be open, colorbox may have single or multiple images, if multiple then next and prev should be working.
[enter image description here][1]
<td>
<a class="view_attachments" expense_id="{{$expense->id}}" href="javascript:;">
<span class="glyphicon glyphicon-picture"></span>
</a>
{{--<span class="glyphicon glyphicon-picture"></span> --}}
<div>
#foreach($expense->attachments as $attachment)
<p>
<a class="group
<?php echo intval($expense->id);?>" href="{{asset("expense_attachments/voucher-" . $voucher_id ."/" . intval($expense->id) ."/" . $attachment->file_name . "")}}" title="">
</a>
</p>
#endforeach
</div>
</td>
<script>
$(function(){
$("a.view_attachments").on('click', function() {
var expense_id = $(this).attr("expense_id");
var $gallery = $(".group" + expense_id).colorbox({rel:'group' + expense_id,slideshow:true,width:'auto',innerWidth:'auto'});
$(".group" + expense_id).colorbox({rel:'group' + expense_id,slideshow:true,width:'auto',innerWidth:'auto'});
//e.preventDefault();
$gallery.eq(0).click();
});
});
// function view_attachments(expense_id)
// {
// //alert(expense_id);
// //$(".attachments" + expense_id).show();
// $.colorbox({rel:'group' + expense_id,width:'70%',innerWidth:'100%'});
// //$(".group" + expense_id).colorbox({rel:'group' + expense_id, slideshow:true});
// }
</script>
[1]: https://i.stack.imgur.com/Rf9eh.jpg

How to input a number on an Internet Explorer element?

I am trying to input a number on an IE element (input) from Excel VBA.
I am not a HTML developer, but there are some frame codes that might influence my problem.
This is what I have in VBA:
IE.Navigate "http://thisandthat/herewego.asp"
IE.Document.getElementsbyId("txt_cod_re_rh").Value = "aaaa"
Nothing happens.
I also tried to get the element ID or test if VBA could see it, but it looks like VBA cannot find it on the page (tried ID and class):
Set element = Document.getElementByclass("select_st")
ThisWorkbook.Sheets(1).Range("b1").Value = element
This is my HTML:
<SCRIPT LANGUAGE="VBS">
smthing
</SCRIPT>
<HTML>
<HEAD>
<link href="../css/standard.css" rel="stylesheet" type="text/css">
<script language="JavaScript" src="include/scripts.js"></script>
<script language="JavaScript">
function exibeRelatorierer(server) {
d = window.document.frmFilter;
var cod_VP = d.cbo_VP;
var cod_periodo = d.cbo_Periodoerer;
var cod_re_rh = d.txt_cod_re_rh;
if (cod_re_rh.value == '') {
cod_re_rh.value = "0";
}
if (cod_periodo.value == -1) {
alert("Select smthing.");
}else{
if (d.TC[0].checked) {
parent.frames['frmMain'].location = servidor234234 + "RPT_CPR01884_TS" + "&rc:Area=Toolbar&rc:LinkTarget=frmMain&rc:JavaScript=True&rs:ClearSession=true&rc:Parameters=false" + "&COD_VP=" + cod_VP.value + "&COD_PERIODO=" + cod_periodo.value + "&COD_RE_RH=" + cod_re_rh.value
} else {
parent.frames['frmMain'].location = servidor234234 + "RPT_CPR01884_CP" + "&rc:Area=Toolbar&rc:LinkTarget=frmMain&rc:JavaScript=True&rs:ClearSession=true&rc:Parameters=false" + "&COD_VP=" + cod_VP.value + "&COD_PERIODO=" + cod_periodo.value + "&COD_RE_RH=" + cod_re_rh.value
}
I believe this code above is messing me up trying to insert value to the txt_cod_re_rh.
I read something about a frame? Is this element on another frame? (No idea, really.)
This is the code where the input box is:
<form id="Form1" name="frmFiltro">
<table border="0" width="100%" cellpadding="0" cellspacing="0">
<tr class="table_bhoras1" height="50" align="center">
<td>Extração</td>
</tr>
</table>
<table id="Table3" cellSpacing="0" cellPadding="0" width="100%" border="0" class="titsemlink2">
<TR class="titsemlink2">
<td>
Inform number:
</td>
<td>
<input class="select_st" type="text" name="txt_cod_re_rh" id="txt_cod_re_rh" value="" />
</td>
</TR>
You have typos in your code. The methods .getElementsbyId or getElementByclass do not exist within the InternetExplorer document object in VBA.
You can try this via element id:
Set element = IE.Document.getElementById("txt_cod_re_rh")
element.value = "aaaa"
Or via classname:
Set element = IE.Document.getElementsByClassName("select_st")(0)
element.value = "aaaa"
Withou the full html is difficult to tell if it is inside an iframe or not.

Dynamically set value for asp-route-id using javascript without foreach loop

I am working on an ASP.Net MVC 6 application. The default index view usually has links for Edit, Details and Delete inside the foreach loop like
#foreach (var item in Model) {
<tr>
<td>#Html.DisplayFor(modelItem => item.FirstName)</td>
<td>#Html.DisplayFor(modelItem => item.LastName)</td>
<td>
<a asp-action="Edit" asp-route-id="#item.SpeakerId">Edit</a> |
<a asp-action="Details" asp-route-id="#item.SpeakerId">Details</a> |
<a asp-action="Delete" asp-route-id="#item.SpeakerId">Delete</a>
</td>
</tr>
}
My requirement is such that the links for View, Edit & Delete should appear outside the table and the row should be selected using radio buttons column.
Is there any way to set the asp-route-id attribute dynamically using the onchange event of radiobutton?
I have tried something link this
function radioSelected() {
var routeId = $('input[name="selectRecord"]:checked').val();
var links = "<a asp-action='Details' asp-route-id=" + routeId + ">View Details</a> | "
+ "<a asp-action='Edit' asp-route-id=" + routeId + ">Edit</a> | "
+ "<a asp-action='Delete' asp-route-id=" + routeId + ">Delete</a>";
document.getElementById("actions").innerHTML = links;
}
but the asp-route-id and asp-action attributes don't work this way.
If possible, you can use jquery. I added below part to handle your case:
<a id="lnkEdit" data-url-prefix="#Url.Action("Edit")">Edit</a> |
<table id="tableSelect">
#foreach (var item in Model)
{
<tr data-item-id="#item.SpeakerId">
<td><input name="selectRow" type="radio"></td>
<td>#Html.DisplayFor(modelItem => item.FirstName)</td>
<td>#Html.DisplayFor(modelItem => item.LastName)</td>
</tr>
}
</table>
<script type="text/javascript">
$(function () {
$('#tableSelect tr').click(function () {
$(this).find('td input:radio').prop('checked', true);
$("#lnkEdit").attr("href", $("#lnkEdit").data("url-prefix") + "/" + $(this).data("item-id"));
})
});
</script>

How to add autocomplete data into invoice dynamically

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.