I have the following data in the database. I want to populate my text fields by populating this data using servlets and ajax.
data_id ------------------------ char(30)
Lat --------------------------double precision
Long ------------------------- double precision
Info.class
package org.bean
public class Info {
private String data_id;
private String lat;
private String long;
public void setData_id(String data_id) {
this.data_id = data_id;
}
public String getData_id() {
return data_id;
}
public void setLat(String lat) {
this.lat = lat;
}
public String getLat() {
return lat;
}
public void setLong(String long) {
this.long = long;
}
public String getLong() {
return long;
}
}
FetchData.class
public class FetchData {
private static Connection connection = null;
public static Connection getConnection() {
if (connection != null)
return connection;
else {
try {
Properties prop = new Properties();
InputStream inputStream =
FetchData.class.getClassLoader().getResourceAsStream("/db.properties");
prop.load(inputStream);
String driver = prop.getProperty("driver");
String url = prop.getProperty("url");
String user = prop.getProperty("user");
String password = prop.getProperty("password");
Class.forName(driver);
connection = DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return connection;
}
}
public static ArrayList<Info> getAllInfo() {
connection = FetchData.getConnection();
ArrayList<Info> inf = new ArrayList<Info>();
try {
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("select * from info_table");
while(rs.next()) {
Info in=new Info();
in.setData_id(rs.getString("data_id"));
in.setLat(rs.getString("Lat"));
in.setLong(rs.getString("Long"));
inf.add(in);
}
} catch (SQLException e) {
e.printStackTrace();
}
return inf;
}
}
PopulateTable.class
public class PopulateTable extends HttpServlet {
private static final long serialVersionUID = 1L;
public PopulateTable() {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ArrayList<Info> in=new ArrayList<Info>();
in=FetchData.getAllInfo();
Gson gson = new Gson();
JsonElement element = gson.toJsonTree(in, new TypeToken<List<Info>>() {}.getType());
JsonArray jsonArray = element.getAsJsonArray();
response.setContentType("application/json");
response.getWriter().print(jsonArray);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
index.jsp
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#tablediv").hide();
$("#showTable").click(function(event){
$.get('PopulateTable',function(responseJson) {
if(responseJson!=null){
$("#infotable").find("tr:gt(0)").remove();
var table1 = $("#infotable");
$.each(responseJson, function(key,value) {
var rowNew = $("<tr><td></td><td></td><td></td></tr>");
rowNew.children().eq(0).text(value['data_id']);
rowNew.children().eq(1).text(value['lat']);
rowNew.children().eq(2).text(value['long']);
rowNew.appendTo(table1);
});
}
});
$("#tablediv").show();
});
});
</script>
</head>
<input type="button" value="Show Table" id="showTable"/>
<br/>
<br/>
<div id="tablediv">
<table cellspacing="0" id="infotable">
<tr>
<th scope="col">Data_id</th>
<th scope="col">Latitude</th>
<th scope="col">Longitude</th>
</tr>
</table>
</div>
</body>
</html>
I am basically populating the database data in a table using servlets and ajax on a jsp page without refreshing the page. I want the same action to be taken. Instead of onclick of a button I want the user to enter data_id and onkeyup event of that textfield Latitude and longitude values to be populated from the database. how do i do this.
If i change the jsp page to
<input type="text" id="data_id" onblur=""/>
<input type="text" id="latitude"/>
<input type="text" id="longitude"/>
then onblur event should populate my textfields having id latitude and longitude with the data corresponding to the typed id. How do i do this?
Instead of putting your Ajax call inside $(document).ready(function() {...}); put it in a function with a name and have your onblur call it:
function populatefields()
{
... //Ajax stuff
}
...
...
<input type="text" id="data_id" onblur="populatefields()" />
<%#page import="java.util.logging.Logger"%>
<%#page import="java.util.logging.Level"%>
<%#page import="java.sql.SQLException"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.Statement"%>
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.Connection"%>
<%#page import="javax.swing.JFrame"%>
<%#page import="javax.swing.JButton"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Student view</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<script>
function selectItem()
{
var sel=document.getSelection("drop").value;
var c=document.getElementById("drop").value;
var xmlhttp,url;
if(c=="hand")
url="StudentView_2.jsp";
else
url="StudentView.jsp";
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest(); //for IE7+, Firefox, Chrome, Opera, Safari
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); //for IE6, IE5
}
xmlhttp.open("GET",url,true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200)
{
document.getElementById("message1").innerHTML = xmlhttp.responseText;
}
else
{
alert('Something is wrong !!');
}
}
}
}
</script>
</head>
<body>
<div id="topPan"> <!--<img src="" alt="Education Zone" width="245" height="37" border="0" class="logo" title="Education Zone"/>-->
<h1> <p>Library Manager</p></h1>
<div id="topContactPan"> </div>
<div id="topMenuPan">
<div id="topMenuLeftPan"></div>
<div id="topMenuMiddlePan">
<ul>
<li class="home">Home</li>
<li>Logout</li>
<!-- <li class="contact">Contact</li>-->
</ul>
</div>
<div id="topMenuRightPan"></div>
</div>
</div>
<div id="bodyPan">
<div id="bodyLeftPan">
<h2><span>Student View</span> </h2>
<!-- <p>Education Zone is a free, tableless, W3C-compliant web design layout by <span>Template World</span>. This template has been tested and proven compatible with all major browser environments and operating systems. You are free to modify the design to suit your tastes in any way you like.</p>
<p>We only ask you to not remove "Design by Template World" and the link <span>http://www.templateworld.com</span> from the footer of the template.</p>
<p>If you are interested in seeing more of our free web template designs feel free to visit our website, Template World. We intend to add at least 25 new <span>free templates</span> in the coming month.</p>
-->
<!-- <form action="StudentView_1.jsp">
<input type="submit" value="View All Books" >
</form>
<form action="StudentView_2.jsp">
<input type="submit" value="In Hand" >
</form> -->
<form >
<select name="drop" id="drop" onchange="selectItem()">
<option value="view" >View All</option>
<option value="hand">In Hand</option>
</select>
<!--<input type="" value="In Hand" >-->
</form>
<%
// try{
// // TODO add your handling code here:
// String [] colname={"Book Id","Book Name","Book Author"};
// Class.forName("com.mysql.jdbc.Driver");
// Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/sample","root","mysql");
// Statement st=conn.createStatement();
// System.out.println("success");
// String sql1="select * from book where Available='1'";
// ResultSet rs=st.executeQuery(sql1);
// int n=0,i=0;
// while(rs.next())
// {
// n++;
// }
// rs.beforeFirst();
// Object [][] o=new Object[n][3];
// out.println("<table border=1>");
// out.println("<tr><td>Book Id</td><td>Book Name</td><td>Book Author</td></tr>");
//
// while(rs.next())
// {
// o[i][0]=rs.getString(1);
// o[i][1]=rs.getString(2);
// o[i][2]=rs.getString(3);
// out.println("<tr><td>"+o[i][0]+"</td><td>"+o[i][1]+"</td><td>"+o[i][2]+"</td></tr>");
// i++;
// }
// out.println("</table>");
//
// }catch(Exception ee)
// {
//
// }
// Object ss=request.getParameter("xx");
//System.out.println(ss);
// session.setAttribute("pp",ss );
%>
</div>
<form>
</form>
<div id="message1" class="aaa">
<%# page language="java" contentType="text/html; charset=ISO-8859-1" %>
<%# page import="java.sql.PreparedStatement" %>
<%# page import="java.sql.ResultSet" %>
<%# page import="java.sql.Connection" %>
<%# page import="java.sql.DriverManager" %>
<%!
public int Converter(String str)
{
int convrtr=0;
if(str==null)
{
str="0";
}
else if((str.trim()).equals("null"))
{
str="0";
}
else if(str.equals(""))
{
str="0";
}
try{
convrtr=Integer.parseInt(str);
}
catch(Exception e)
{
}
return convrtr;
}
%>
<%
Connection con = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sample","root", "mysql");
ResultSet rsPgin = null;
ResultSet rsRwCn = null;
PreparedStatement psPgintn=null;
PreparedStatement psRwCn=null;
// Number of records displayed on each page
int iSwRws=4;
// Number of pages index displayed
int iTotSrhRcrds=10;
int iTotRslts=Converter(request.getParameter("iTotRslts"));
int iTotPags=Converter(request.getParameter("iTotPags"));
int iPagNo=Converter(request.getParameter("iPagNo"));
int cPagNo=Converter(request.getParameter("cPagNo"));
int iStRsNo=0;
int iEnRsNo=0;
if(iPagNo==0)
{
iPagNo=0;
}
else{
iPagNo=Math.abs((iPagNo-1)*iSwRws);
}
String sqlPgintn="SELECT SQL_CALC_FOUND_ROWS * FROM book limit "+iPagNo+","+iSwRws+"";
psPgintn=con.prepareStatement(sqlPgintn);
rsPgin=psPgintn.executeQuery();
// Count total number of fetched rows
String sqlRwCnt="SELECT FOUND_ROWS() as cnt";
psRwCn=con.prepareStatement(sqlRwCnt);
rsRwCn=psRwCn.executeQuery();
if(rsRwCn.next())
{
iTotRslts=rsRwCn.getInt("cnt");
}
%>
<html>
<head>
<title>Pagination using JSP page</title>
</head>
<body>
<form name="frm">
<input type="hidden" name="iPagNo" value="<%=iPagNo%>">
<input type="hidden" name="cPagNo" value="<%=cPagNo%>">
<input type="hidden" name="iSwRws" value="<%=iSwRws%>">
<table cellpadding="0" cellspacing="0" border="1" >
<tr>
<td>BookId</td>
<td>BookName</td>
<td>BookAuthor</td>
</tr>
<%
while(rsPgin.next())
{
%>
<tr>
<td><%=rsPgin.getString(1)%></td>
<td><%=rsPgin.getString(2)%></td>
<td><%=rsPgin.getString(3)%></td>
<td><a href="www.google.com>view </a></td>
</tr>
<%
}
%>
<%
// Calculate next record start and end position
try{
if(iTotRslts<(iPagNo+iSwRws))
{
iEnRsNo=iTotRslts;
}
else
{
iEnRsNo=(iPagNo+iSwRws);
}
iStRsNo=(iPagNo+1);
iTotPags=((int)(Math.ceil((double)iTotRslts/iSwRws)));
}
catch(Exception e)
{
e.printStackTrace();
}
%>
<tr>
<td colspan="3">
<div>
<%
// Create index of pages
int i=0;
int cPge=0;
if(iTotRslts!=0)
{
cPge=((int)(Math.ceil((double)iEnRsNo/(iTotSrhRcrds*iSwRws))));
int prePageNo=(cPge*iTotSrhRcrds)-((iTotSrhRcrds-1)+iTotSrhRcrds);
if((cPge*iTotSrhRcrds)-(iTotSrhRcrds)>0)
{
%>
<< Previous
<%
}
for(i=((cPge*iTotSrhRcrds)-(iTotSrhRcrds-1));i<=(cPge*iTotSrhRcrds);i++)
{
if(i==((iPagNo/iSwRws)+1))
{
%>
<b><%=i%></b>
<%
}
else if(i<=iTotPags)
{
%>
<%=i%>
<%
}
}
if(iTotPags>iTotSrhRcrds&& i<iTotPags)
{
%>
>> Next
<%
}
}
%>
<b>Rows <%=iStRsNo%> - <%=iEnRsNo%> Total Result <%=iTotRslts%></b>
</div>
</td>
</tr>
</table>
</form>
</body>
</html>
<%
try{
if(psPgintn!=null){
psPgintn.close();
}
if(rsPgin!=null){
rsPgin.close();
}
if(psRwCn!=null){
psRwCn.close();
}
if(rsRwCn!=null){
rsRwCn.close();
}
if(con!=null){
con.close();
}
}
catch(Exception e)
{
e.printStackTrace();
}
%>
</div>
<!--<table id="message1" align="left" width="200" border="1" class="aaa">
</table>-->
<!--<form>
<select name="message1" id="message1">
</select>
</form>-->
<div id="bodyRightPan1">
</div>
</div>
<div id="footermainPan">
<div id="footerPan">
<ul>
<li>Home| </li>
<li>Registration| </li>
</ul>
<p class="copyright">©education zone. All right reserved.</p>
<ul class="templateworld">
<li>design by:</li>
<li>Template World</li>
</ul>
<div id="footerPanhtml">HTML</div>
<div id="footerPancss">css</div>
</div>
</div>
</body>
</html>
Related
Scenario:
Creation of a basic HTML form with email, password fields and a submit button using ASP.NET MVC.
Required Cases: (1) Strongly bounded View - fetching variables from the controller and being defined explicitly as properties in a
Model. (2) Use HTML helpers instead of html tags for the input fields (3)
Provide an option to show/hide the characters while entering the password in the HTML
form on a web browser
The Model - LoginViewModel.cs
public class LoginViewModel
{
[DisplayName("Email")]
public string Email{ get; set; }
[DisplayName("Password")]
public string LoginPassword { get; set; }
}
The Controller - LoginController.cs
public class LoginController : Controller
{
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(LoginViewModel log)
{
var Email = log.Email.ToLower();
var loginPassword = log.LoginPassword;
try
{
//code logic
return View("anotherView");
}
catch (System.Exception)
{
return View("exceptionView");
}
return View("tryAgainView");
}
The View - Index.cshtml
#model Project.Models.LoginViewModel
#{
ViewBag.Title = "Login";
Layout = "~/Views/Shared/_Layout.cshtml";//This view contains custom coding
}
<!--HTML-->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>#ViewBag.Title</title>
#Styles.Render("~/Content/css")
#Scripts.Render("~/Scripts/js")
</head>
<body>
<header>
<div class="container">
<div class="row justify-content-center">
#using (Html.BeginForm("Login", "Login", FormMethod.Post))
{
<div class="content">
<!-- Email input -->
<div class="form-outline">
#Html.TextBoxFor(lvm => lvm.Email, new { #class = "form-control", required = "yes", #type = "email", #autocomplete = "off", #onsubmit = "return process()" })
#Html.LabelFor(lvm => lvm.Email, new { #class = "form-label" })
</div>
<!-- Password input -->
<div class="form-outline">
#Html.PasswordFor(lvm => lvm.LoginPassword, new { #class = "form-control", required = "yes", #autocomplete = "off", #onsubmit = "return process()" })
#Html.LabelFor(lvm => lvm.LoginPassword, new { #class = "form-label" })
</div>
<!-- Insert Submit button logic here -->
</div>
}
</div>
</div>
</div>
</header>
</body>
</html>
Checking the output HTML formatting (via the 'Inspect Element') of the password field
<input autocomplete="off" class="form-control" id="LoginViewModel_LoginPassword" name="LoginViewModel.LoginPassword" onsubmit="return process()" required="yes" type="password">
The Problem:
How do I add the password show/hide logic here? I have tried most of the javascript additions within the View by playing around
with the 'id' property in the HTML output formatting, but in
vain. I request you to please give a working solution which fits
into the implementation that I've presented here.
You'd need something along these lines (assuming you're using jQuery):
<form>
<input id ="pw_input" type="password" />
<button id="toggle">Toggle</button>
</form>
$('#toggle').click(function() {
if ($('#pw_input').attr('type') === "password") {
$('#pw_input').attr('type','text');
}
else {
$('#pw_input').attr('type','password');
}
})
Im trying to add a function to add any amount of user requested textboxes my EventMembers input.
I have the functions working but the additional textbox inputs are not being added to my EventMembers List. I know if i just create multiple textboxes on my view by doing
EventMembers[0]
EventMembers[1]
EventMembers[2]
etc.. That works fine. How would i go about accomplishing the same thing with my javascript functions for dynamic textboxes? Code below with required info only.
Model:
public class Event
{
public List<string> EventMembers { get; set; }
}
View:
<div class="form-group" id="firstdiv">
<label asp-for="EventMembers" class="control-label">Event Members</label>
<input asp-for="EventMembers" class="form-control" />
<input type="button" class="btn btn-primary" value="Add Member"
onclick="DynamicText()" />
<span asp-validation-for="EventMembers" class="text-danger"></span>
<span style="color:red;">#TempData["MustEnterinput"]</span>
</div>
Javascript:
function DynamicText() {
var division = document.createElement('DIV');
division.innerHTML = DynamicTextBox("");
document.getElementById("firstdiv").appendChild(division);
}
function DynamicTextBox(value) {
return '<div><input asp-for="EventMembers" class="form-control" /><input type="button" class="btn btn-primary" onclick="ReTextBox(this)" value="Remove" /></div>';
}
function ReTextBox(div) {
document.getElementById("firstdiv").removeChild(div.parentNode.parentNode);
}
I changed some names for my setup.
Model;
public class EventMemberList
{
public List<string> EventMembers { get; set; }
}
Controller, Get Action;
public IActionResult Index()
{
EventMemberList model = new EventMemberList
{
EventMembers = new List<string>()
};
return View(model);
}
Controller, Post Action;
[HttpPost]
public IActionResult Index(EventMemberList model)
{
//Do Something...
return View(model);
}
Finaly View ;
#using (Html.BeginForm())
{
<div class="form-group" id="firstdiv">
<label class="control-label">Event Members</label>
<div id="inputList"></div>
<br />
<a class="btn btn-primary" onclick="AddInput()">Add Member</a>
<br />
<button type="submit">Submit</button>
</div>
}
<script type="text/javascript">
function AddInput() {
var inputList = document.getElementById("inputList");
var inputCount = inputList.getElementsByTagName('input').length;
var newInput = `
<input class="form-control" id="EventMembers_${inputCount}" name="EventMembers[${inputCount}]" type="text" value="">
<br/>
`;
var element = document.createElement("div");
element.innerHTML = newInput ;
inputList.appendChild(element);
}
</script>
To append input, I created a div. You need to add id like EventMembers_${inputCount} and name like EventMembers[${inputCount}]. With doing this, you will be able to send data to controller.
If you want to some validation in model, you need to add to inputList some code ;
<div id="inputList">
#for (int i = 0; i < Model.EventMembers.Count; i++)
{
#Html.EditorFor(_ => Model.EventMembers[i], new { htmlAttributes = new { #class = "form-control" } })
<br />
}
</div>
By doing this, when you submit list and model is not valid, you will be able to send invalid inputs to view back.
I've been wanted to delete the row by its id.
I've already done "things" in Service, Controller, Listfiles, and the Delete file.
This is the controller
#RequestMapping("/hapussertifikasi")
public String hapussertifikasi() {
return ("sertifikasi/hapussertifikasi");
}
#ResponseBody
#RequestMapping(value = "/hapussertifikasi/{angka}", method = RequestMethod.DELETE)
public Map<String, String> hapussertifikasi(#PathVariable("angka") Long angka, Model model) {
sertifikasisr.hapus(angka);
// key value
Map<String, String> map = new HashMap<>();
// pakai String string karena value key dan value nya string
System.out.println();
System.out.println(angka);
map.put("status", "berhasil");
// DARI BARANG SERVICE
/*
* if(brngsr.hapus(angka)) { // key value map.put("status", "berhasil"); }else {
* map.put("status", "gagal"); }
*/
return map;
}
This is the Service file
public boolean hapus(Long id) {
try {
sertifikasi.deleteById(id);
return true;
}catch(Exception e) {
return false;
}
}
This is the List File
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<!-- Nulis table didalam body -->
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<td>ID</td>
<td>Nama Sertifikasi</td>
<td>Penerbit</td>
<td>Masa Berlaku</td>
<td>#</td>
</tr>
</thead>
<tbody id="idTbodySertifikasi">
<tr th:each="item :${keysertifikasi}">
<td th:text="${item.id}">ID</td>
<td th:text="${item.certificate_name}">NamaBarang</td>
<td th:text="${item.publisher}">JenisBarang</td>
<td th:text="${item.until_year + '-' + item.until_month }">Sampai</td>
<td>
<div class="dropdown">
<button class="btn btn-primary dropdown-toggle" type="button"
data-toggle="dropdown">
More <span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li class="clDropdown" data-value="0">Ubah</li>
<li class="clDropdown" data-value="1">Hapus</li>
</ul>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<script type="text/javascript">
$('.table-responsive').on('show.bs.dropdown', function() {
$('.table-responsive').css("overflow", "inherit");
});
$('.table-responsive').on('hide.bs.dropdown', function() {
$('.table-responsive').css("overflow", "auto");
});
$(".clDropdown").click(function() {
debugger;
var x = $(this).data('value');
var angka = $(this).attr('data-idbarang');
if (x == 0) {
$.ajax({
url : './ubahsertifikasi',
method : 'Get',
success : function(model) {
debugger;
/* jahit model return dari controller ke body modal */
$('#idMdlBodyUbahSertifikasi').html(model);
/* pop up modalnya */
$('#idMdlUbahSertifikasi').modal('show');
},
error : function(model) {
debugger;
}
});
} else if (x == 1) {
debugger;
$.ajax({
url : './hapussertifikasi',
method : 'Get',
success : function(model) {
debugger;
/* jahit model return dari controller ke body modal */
$('#idMdlBodyHapusSertifikasi').html(model);
/* pop up modalnya */
$('#idMdlHapusSertifikasi').modal('show');
},
error : function(model) {
debugger;
}
});
}
});
</script>
</body>
</html>
And lastly this is the delete file where the delete button is placed
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<div class="col-xs-12">
<div class="row">
<div class="col-xs-2">
<i class="glyphicon glyphicon-trash center" style="font-size: 50px"></i>
</div>
<div class="col-xs-8">
<div class="clTulisanHapus center" id="idTulisanHapus">Anda
Yakin ingin menghapus Pelatihan?</div>
</div>
</div>
</div>
<div class="col-md-offset-8">
<div class="btn-group">
<button type="button" id="idBtnHapusBatal" class="btn clBtnMdlHapus">Tidak</button>
<button type="button" id="idBtnHapusHapus" class="btn clBtnMdlHapus">Ya</button>
</div>
</div>
<script>
$('#idBtnHapusHapus').click(function() {
var angka = $(this).attr('data-id');
debugger;
debugger;
$.ajax({
url : '/hapussertifikasi/' + angka,
type : 'DELETE',
success : function(model) {
debugger;
window.location = './sertifikasi'
},
error : function(model) {
debugger;
}
});
});
</script>
</body>
</html>
The id is showing ok, but the id values isn't sending to the Controller file.
The button <button type="button" id="idBtnHapusHapus" class="btn clBtnMdlHapus">Ya</button> has no data-id attribute, thus when calling var angka = $(this).attr('data-id');, angka is Nil.
This means you are making a delete request on /hapussertifikasi/, which is going to return a 400 error because you aren't passing the required argument (correct syntax would be /hapussertifikasi/14 where 14 is the id you want to delete.)
hi bro i also face this type of problem .....
after longtime R&D i found a solution , but i don't know why it's working..
try this
url : 'hapussertifikasi/' + angka,
just remove first /sing
I am having an issue with adding a record held in data.
The inner exception is this:
Invalid column name 'CustomerNames_CustomerId'.
Invalid column name 'CustomerNames_CustomerId'.
Invalid column name 'CustomerNames_CustomerId'.
I cannot figure this out as there is a CustomerId column in CustomerNames. Everything works (adding items to the cart, getting CustomerId), except when you go to save the Order.
That is when I get the error on the Line I have a break.
Contoller Actions (PartsController):
public ActionResult PartsDetail(int id, string mReq)
{
Session["CustomerId"] = id;
if (mReq == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
SubJobDetails modelInstance = SubJobDetails.GetSubjobsAndParts(mReq, db);
//if (modelInstance == null)
//{
// return HttpNotFound();
//}
return View(modelInstance);
}
public static List<SubJobDetails> partsList = new List<SubJobDetails>();
[HttpPost]
public ActionResult AddToShoppingCart(SubJobDetails parts)
{
string message = string.Empty;
if (parts != null)
{
partsList.Add(parts);
message = "product has been added successfully !";
}
else
{
message = "something Wrong !";
}
return Json(new { message = message }, JsonRequestBehavior.AllowGet);
}
// Displays Shopping Cart
public ActionResult ShoppingCart()
{
List<SubJobDetails> myShoppingCart = partsList;
return PartialView("~/Views/Customer/ShoppingCart.cshtml", myShoppingCart);
}
[HttpPost]
public ActionResult AddOrder(string[] arrIdPart, int[] arrQtyPart)
{
int countPart = arrIdPart.Length;
int customerId = (int)Session["CustomerId"];
bool statusTran = false;
CustomerEntities _context = new CustomerEntities();
using (DbContextTransaction dbTran = _context.Database.BeginTransaction())
{
try
{
CustomerNames customer = _context.CustomerNames.Find(customerId);
**Break incerted here, Error appears ->** if (customer != null)
{
**Break Inserted Here, Error appears ->** customer.Ordered.Add(new Orders { OrderDate = DateTime.Now });
}
Orders orderSelected = customer.Ordered.LastOrDefault();
if (orderSelected != null)
{
for (int i = 0; i < countPart; i++)
{
Parts selectedPart = _context.Parts.Find(arrIdPart[i]);
orderSelected.OrderDetail.Add(new OrderDetails { Part = selectedPart, Quantity = arrQtyPart[i] });
}
}
//Save Changes
int countResult = _context.SaveChanges();
//Commit Transaction
dbTran.Commit();
if (countPart > 0)
{
statusTran = true;
partsList.Clear();
}
}
catch (Exception)
{
dbTran.Rollback();
}
}
return Json(new { data = statusTran }, JsonRequestBehavior.AllowGet);
}
}
Models - CustomerNames, CustomerViews and Orders.
public class CustomerNames
{
public CustomerNames()
{
Address = new List<Addresses>();
Ordered = new List<Orders>();
}
[Key]
public int CustomerId { get; set; }
[Display(Name ="Company Name")]
public string CustomerName { get; set; }
public int Status { get; set; }
public string ExemptionForm { get; set; }
[UIHint("_IsStatus")]
public bool ExemptionFormUploaded { get; set; }
public virtual IEnumerable<Addresses> Address { get; set; }
public virtual ICollection<Orders> Ordered { get; set; }
}
Orders:
public class Orders
{
public Orders()
{
OrderDetail = new List<OrderDetails>();
}
[Key]
public int OrderId { get; set; }
public DateTime OrderDate { get; set; }
public string PONumber { get; set; }
public bool UseCreditCard { get; set; }
public virtual CustomerNames CustomerNames { get; set; }
//public virtual Addresses Addresses { get; set; }
public virtual ICollection<OrderDetails> OrderDetail { get; set; }
}
ViewModel:
public partial class SubJobDetails
{
public static SubJobDetails GetSubjobsAndParts(string mReq, CustomerEntities db)
{
var Parts = from pts in db.PartsView
join sj in db.SubJobs on pts.SubJob equals sj.SubJob
join tlj in db.TopLvlJobs on sj.TopLvlJob equals tlj.TopLvlJob
join se in db.SerialNumbers on tlj.TopLvlJob equals se.TopLvlJob
where (pts.SubJob == mReq)
select new SubJobDetails()
{
PartsView = pts,
TopLvlJob = tlj.TopLvlJob,
SubJobs = sj,
Material = pts.Material,
Description = pts.Description,
SellingPrice = pts.SellingPrice,
UnitsInStock = pts.UnitsInStock,
PartImage = pts.PartImage,
CustomerId = se.CustomerId
};
var result = Parts.FirstOrDefault();
if (result != null)
{
result.PartsDetail = db.PartsView.Where(a => a.SubJob == result.PartsView.SubJob);
};
return result;
}
public int CustomerId { get; set; }
public string Material { get; set; }
public string Description { get; set; }
public decimal SellingPrice { get; set; }
public int UnitsInStock { get; set; }
public string PartImage { get; set; }
public string LeadTime { get; set; }
public int QtySelected { get; set; }
public string TopLvlJob { get; set; }
public virtual TopLvlJobs TopLvlJobs { get; set; }
public virtual PartsView PartsView { get; set; }
public virtual SubJobs SubJobs { get; set; }
public virtual IEnumerable<PartsView> PartsDetail { get; set; }
}
View:
#model BestenEquipment.Models.SubJobDetails
#{
ViewBag.Title = "PartsDetail";
Layout = "~/Views/Shared/CustomerDashboardLayout.cshtml";
}
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<div id="page-wrapper">
<div class="row">
<div class="col-lg-12">
<p>
<br />
<h4> #Html.DisplayFor(model => model.SubJobs.Description) </h4>
#Html.ActionLink("Back to Machine Detail", "MachineDetail", null, new { Job = Model.TopLvlJob }, new { #class = "btn btn-default" })
<div style="float:right;">
<button type="button" data-toggle="modal" data-target="#exampleModal" class="btn btn-primary" id="myOrder">
<span class="glyphicon glyphicon-shopping-cart"></span> My Order
</button>
</div>
</p>
</div>
<!-- /.col-lg-12 -->
</div>
<div class="row">
<div class="col-lg-12">
<div>
<hr />
<dl class="dl-horizontal">
<dt>
#Html.DisplayNameFor(model => model.SubJobs.ExtDescription)
</dt>
<dd>
#Html.DisplayFor(model => model.SubJobs.ExtDescription)
</dd>
<dt>
#Html.DisplayNameFor(model => model.SubJobs.PartNumber)
</dt>
<dd>
#Html.DisplayFor(model => model.SubJobs.PartNumber)
</dd>
<dt>
#Html.DisplayNameFor(model => model.SubJobs.Drawing)
</dt>
<dd>
#Html.DisplayFor(model => model.SubJobs.Drawing)
</dd>
</dl>
</div>
</div>
<!-- /.col-lg-12 -->
</div>
<div class="row">
<div class="col-lg-12">
<div class="container" style="float:left;">
<div class="well well-sm">
<strong>Display</strong>
<div class="btn-group">
<a href="#" id="list" class="btn btn-default btn-sm">
<span class="glyphicon glyphicon-th-list">
</span>List
</a> <a href="#" id="grid" class="btn btn-default btn-sm">
<span class="glyphicon glyphicon-th"></span>Grid
</a>
</div>
</div>
<div id="products" class="row list-group">
#foreach (var item in Model.PartsDetail)
{
<div class="item col-sm-3 col-lg-3">
<div class="thumbnail">
#if (item.PartImage != null)
{
<img class="group list-group-image" src="#Html.DisplayFor(model => item.PartImage)" alt="" />
}
else
{
<img class="group list-group-image" src="~/Content/Images/NoImage.png" alt="" />
}
<div class="caption">
<h4 class="group inner list-group-item-heading">
#Html.DisplayFor(model => item.Material), #Html.DisplayFor(model => item.Status)
</h4>
<p class="group inner list-group-item-text">
#Html.DisplayFor(model => item.Description)
</p>
<div class="row">
#if (item.InStockQuanex == true)
{
<div class="col-xs-12 col-md-12">
<p class="group inner list-group-item-text" style="color:red; font-size:14px !important; padding:13px">
This item is in stock at Quanex. Please call your CSR to order.
</p>
</div>
}
else
{
<div class="col-xs-12 col-md-6">
Units in stock: #Html.DisplayFor(model => item.UnitsInStock)<br />
Lead Time: #Html.DisplayFor(model => item.LeadTime)<br />
<input id="Qty_#item.Material" class="form-control" onfocus="if (this.value == 'Quantity') { this.value = '1' }" onblur="if (this.value == '') { this.value='Quantity' }" value="Quantity" />
</div>
<div class="col-xs-12 col-md-6">
<p class="lead">
#Html.DisplayFor(model => item.SellingPrice)
#Html.DisplayFor(model => item.UnitOfMeasure)
</p>
<a class="btn btn-success" id="test" role="button"
data-material="#item.Material"
data-partImage="#item.PartImage"
data-description="#item.Description"
data-sellingPrice="#item.SellingPrice">
Add To Cart
</a>
</div>
}
</div>
</div>
</div>
</div>
}
</div>
</div>
</div>
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /#page-wrapper -->
<!-- MODAL -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="exampleModalLabel"> <span class="glyphicon glyphicon-shopping-cart"></span> Order </h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div> <!-- MODEL HEADER-->
<div class="modal-body">
</div> <!-- MODAL BODY-->
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$('#list').click(function (event) { event.preventDefault(); $('#products .item').addClass('list-group-item'); });
$('#grid').click(function (event) { event.preventDefault(); $('#products .item').removeClass('list-group-item'); $('#products .item').addClass('grid-group-item'); });
$('.btn-success').click(function () {
var selectedPart = {
Material: $(this).attr('data-material'),
PartImage: $(this).attr('data-partImage'),
Description: $(this).attr('data-description'),
SellingPrice: $(this).attr('data-SellingPrice'),
QtySelected: $('#Qty_' + $(this).attr('data-material')).val()
};
console.log(selectedPart);
$.ajax({
type: 'POST',
url: '#Url.Action("AddToShoppingCart", "Parts")',
data: selectedPart,
success: function (response) {
alert(response.message);
},
error: function (response) {
alert(response.message);
}
});
});
$("#myOrder").click(function () {
$(".modal-body").html('');
$.ajax({
type: 'GET',
url: '#Url.Action("ShoppingCart", "Parts")',
success: function (response) {
$(".modal-body").html(response);
$("#exampleModal").modal('show');
},
error: function () {
alert("Something Wrong");
}
});
});
});
</script>
ShoppingCart Model:
#model IEnumerable<BestenEquipment.Models.SubJobDetails>
#{
decimal totalOrder = 0;
}
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
#if (Model != null && Model.Any())
{
using (Html.BeginForm("AddOrder", "Customer", new { id = "f" }))
{
<table id="tableOrder" class="table table-hover">
<tr>
<th>Part Number</th>
<th>Unit Price</th>
<th>Qty Selected</th>
<th>Description</th>
<th>Total Price</th>
</tr>
#foreach (var parts in Model)
{
<tr>
<td>#parts.Material</td>
<td>#string.Format("{0:C2}", parts.SellingPrice)</td>
<td>#parts.QtySelected</td>
<td>#parts.Description</td>
<td>#string.Format("{0:C2}", (parts.SellingPrice * parts.QtySelected))</td>
</tr>
totalOrder += (parts.QtySelected * parts.SellingPrice);
#Html.HiddenFor(p => parts.Material)
#Html.HiddenFor(p => parts.QtySelected)
}
</table>
<!-- TOTAL PRICE-->
<h4 style="margin-left: 66%;">Total : <span class="label label-info">#string.Format("{0:C2}", totalOrder)</span></h4>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" id="close" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="SaveOrder">Save Order</button>
</div> <!-- MODAL FOOTER-->
}
}
else
{
<div class="alert alert-warning" role="alert">Your basket is empty !</div>
}
<!--JS-->
<script type="text/javascript">
$(document).ready(function () {
//add class rounded img-thumbnail to img tag
$('img').addClass('rounded img-thumbnail');
//Save Order
$("#SaveOrder").click(function () {
var $form = $(this).closest('form');
var dataPart = $form.serializeArray();
console.log(dataPart);
var arrIdPart = [];
var arrQtyPart = [];
for (i = 0; i < dataPart.length; i++)
{
if (dataPart[i].name == 'parts.Material')
{
arrIdPart.push(dataPart[i].value);
}
else if (dataPart[i].name == 'parts.QtySelected')
{
arrQtyPart.push(dataPart[i].value);
}
}
$.ajax({
type: 'POST',
url: '#Url.Action("AddOrder", "Parts")',
data: { arrIdPart, arrQtyPart },
success: function (response) {
if(response.data == true)
{
alert("Order has saved successfully ");
}
else
{
alert("Something Wrong ! ");
}
},
error: function (error) {
alert("Something Wrong ! ");
}
});
});
});
</script>
#model MVC_STORE.Models.Product
#{
Layout = null;
}
<!DOCTYPE html>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>AddProduct</title>
</head>
<body>
<div>
<form id="formAdd" onsubmit=" return SendData(); return false;">
<table>
<tr>
<td>Serial number:</td>
<td>#Html.TextBoxFor(m => m.SerialNo) #Html.ValidationMessageFor(m => m.SerialNo)</td>
</tr>
<tr>
<td>Product name:</td>
<td>#Html.TextBoxFor(m => m.Name) #Html.ValidationMessageFor(m => m.Name)</td>
</tr>
<tr>
<td>Product price:</td>
<td>#Html.TextBoxFor(m => m.Price) #Html.ValidationMessageFor(m => m.Price)</td>
</tr>
<tr>
<td>Product quatity:</td>
<td>#Html.TextBoxFor(m => m.Quatity) #Html.ValidationMessageFor(m => m.Quatity)</td>
</tr>
</table>
<input type="submit" id="toAdd" value="Add product" />
</form>
#Html.Partial("ProductsTable")
<script language="javascript">
function SendData() {
$("#status").text("Saving product, please wait..");
var formData = $("#formAdd").serialize();
$.post("addProduct", formData, BindData);
$("#status").text("");
}
</script>
</div>
</body>
</html>
the onsubmit doesn't work for some reason, and I've read a lot of posts about it, but none of them helped me in this case.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace HW_MVC_STORE.Models
{
public class Product
{
[Key]
[RegularExpression("^[a-zA-Z0-9]+$", ErrorMessage = "Only upper- and lower- case letters and numbers.")]
[Required]
[StringLength(5,MinimumLength=5, ErrorMessage = "Please enter 5 characters serial.")]
public string SerialNo { get; set; }
[RegularExpression("^[a-zA-Z]+$", ErrorMessage = "Only upper- and lower- case letters")]
[Required]
[StringLength(10, MinimumLength=2, ErrorMessage="Please enter between 2 and 10 characters.")]
public string Name { get; set; }
[RegularExpression("^[0-9]+$", ErrorMessage = "Integers only")]
[Required]
public string Quatity { get; set; }
[RegularExpression("^([0-9]+[.][0-9]+)|([1-9]+[0-9]*)$", ErrorMessage = "Numbers only, bigger then zero")]
[Required]
public string Price { get; set; }
}
}
I've tried some suggestions from posts, but none of them worked.
<form id="formAdd" onsubmit="return SendData(); return false;">
<form id="formAdd" onsubmit="return SendData();">
<form id="formAdd" onsubmit="SendData()">
I don't understand why it's even calls the SendData() function, it doesn't suppose to leave the form until all the text-boxes are correctly filed.
how can I fix it or at least what is wrong with it?
You need:
<form id="formAdd" onsubmit="SendData(); return false;">
the function SendData doesn't return a value, thus return SendData(); doesn't make sense.
not returning false would cause a reload of the page (default action)
If the ajax POST in SendData is not working, we need more details on that.