How to write code in html for retrieving the session value.? - html

I have a Default2.cs file which stores a value in session
TextBox1.Text = "Haii";
Session["name"] = TextBox1.Text;
and i need to retrieve it in an html page- Default.aspx
<script runat="server">
Sub Page_Load
string na=(string)Session["name"];
Label1.Text=na;
End Sub
</script>
it shows an error 'String' is a class type and cannot be used as an expression.
please help

Try this in HTML in Defaul.aspx,
<% string na=(string)Session["name"]; %>
<label id="Label1"><% =na %></label>

For ASPX Engine:
Enclose your code in <% Your Code here %>
<% string na=(string)Session["name"]; %>
For Razor Engine:
Enclose your code in #{ Your Code here }
#{
string na=(string)Session["name"];
}

Related

For loops in ejs

I have a array containing some html content like this.
const articleArray=['<p>first text</p>\r\n','<p>second text></p>\r\n','<p>third text</p>\r\n']
I need to render this in an ejs file through a get request
request.render('viewArticles',{array : articleArray})
where 'viewArticles' is an ejs file. I have used the middleware to set the view engine as ejs.
This is the code in ejs
<% for(arr in array) {%>
arr
<% } %>
I am not able to render any html. How to solve this?
'<%- %>' this is help to print html code as it is.
<% 'Scriptlet' tag, for control-flow, no output
<%_ ‘Whitespace Slurping’ Scriptlet tag, strips all whitespace before it
<%= Outputs the value into the template (HTML escaped)
<%- Outputs the unescaped value into the template
<%# Comment tag, no execution, no output
<%% Outputs a literal '<%'
%> Plain ending tag
-%> Trim-mode ('newline slurp') tag, trims following newline
_%> ‘Whitespace Slurping’ ending tag, removes all whitespace after it
for refrence please click visit this site EJS
<% array.forEach(function(item) {%>
<%-item%>
<% }) %>
Try this
<% array.forEach(function(item,index){ %>
<%= item %>
<% }) %>
I'm not really sure how to do what you want exactly , but take a look at this:
First, instead of you creating an array of HTML elements, how about you create an array of objects, like so :
const articles = [{text: "first text"} , {text: "second text"}, {text: "third text"}];
this way you just have to write the HTML once, and I am fairly new to programming but I don't see a scenario where you would get a response in HTML, usually you query a database for data or from a JSON file... and assuming the array is actually getting passed to the .ejs file, lets iterate though it,
<% for(let a of articles){ %>
<p> <%= a.text %> </p>
</br>
<% } %>
If the array is NOT getting passed, check for these in your code :
// If you installed
..."dependencies" : {
"ejs": "x.x.x",
} //Check the package.json file
// If you imported correctly
import ejs = require("ejs");
// If you specified the views path
app.set("views", path.join(__dirname, "views"));
// And the views engine
app.set("view engine", "ejs");
// And your route
request.render('viewArticles',{ articles : articles }) // Check if the file name is correct, I get this wrong many times

Displaying tags after selecting a dropdown

I have 2 column in mysql database, name and value. there are multiple rows for these columns. I need to display name in a dropdown on a jsp page and depending upon what name is selected, its value should be displayed below.
Please provide some piece of code.
my piece of code:-
<%
try{
conn= ConnectionHelper.getConnection();
pstmt=conn.prepareStatement("select name, value from myDb ");
rs=pstmt.executeQuery();
%>
<select id="selectDropDown" name="filename" >
<% while(rs.next()){ %>
<option ><%= rs.getString("name")%> </option>
<% } %>
</select>
value :<%= rs.getString("value")%>
<%
} catch (SQLException sq) {
out.println("OOps! Something went wrong. DB error!");
sq.printStackTrace();
} catch (Exception e) {
out.println("OOps! Something went wrong.");
e.printStackTrace();
} finally {
}
%>
Im not sure how you code, but this is how i code. Maybe you can follow this way to do it. Use two jsp file
jsp
<%
Vector vName = new Vector();
String SQL = "SELECT NAME FROM TB_TEST";
DB_TEST.makeConnection();
DB_TEST.executeQuery(SQL);
while(DB_TEST.getNextQuery())
{
String sNAME = DB_TEST.getColumnString("NAME");
vName.addElement(sNAME);
}
DB_TEST.takeDown();
%>
javascript part
function fnTest()
{
var test_value = document.mainform.TEST_NAME.value;
document.mainform.action = "pop_test2.jsp?value="+test_value;
document.mainform.submit();
}
html
<select name="TEST_NAME" onchange="fnTest();">
<option value="">--- Please Select ---</option>
<%
for (int i=0;i<vNAME.size();i++) {
String sNAME= (String) vNAME.elementAt(i);
%>
<option value="<%=sNAME%>" ><%= sNAME%></option>
<%}%>
</select>
<input type="text" name="TEST_VALUE" value="">
Once you select the name from drop down list it will redirect to pop_test2.jsp
pop_test2.jsp
<%
String sNAME = request.getParameter("value");
String sVALUE = "";
String SQL = "SELECT VALUE FROM TB_TEST WHERE NAME='"+sNAME+"' ";
DB_TEST.makeConnection();
DB_TEST.executeQuery(SQL);
while(DB_TEST.getNextQuery())
{
sVALUE = DB_TEST.getColumnString("VALUE");
}
DB_TEST.takeDown();
%>
<script language="Javascript">
parent.document.mainform.TEST_VALUE.value = "<%=sVALUE%>";
</script>

Load html from returned string

I have the string and its returning function in the code-behind:
string xmlContents = "<ul><li>Installation<br /><ul><li>Startup</li><li>Getting there</li><li>Steps</li>" +
"<li>Pictures</li></ul></li><li>Usage<br /><ul><li>Tilbud pane</li><li>Report pane</li>" +
"</ul></li></ul>";
public String returnXml()
{
return xmlContents;
}
Then I call it in the aspx file:
<div id="treeviewMenu">
<%returnXml(); %>
</div>
When I simply write the html code (of the list) directly in the div - it's ok. But by passing the string - it doesn't work.
What am I doing wrong and how to fix it ?
Note: = sign whithout ; sign
Replace with this code:
<div id="treeviewMenu">
<%=returnXml() %>
</div
You can easily assign html to div by making div server accessible by adding runat="server"
HTML
<div id="treeviewMenu" runat="server"></div>
In code behind
treeviewMenu.InnerHTML = xmlContents;

Retrieving Form collection data from action methods using mvc 2.0

I am developing a sample in asp.net MVC 2.0. In My view (ProductDetails.aspx) I have 3 link buttons which are calling different action methods present in the same controller (ProductController). When I am clicking on the search link the appropriate action method is called but when I am taking data from Form Collection using string pid=Request.Form["tbPid"] I am getting a null value into pid. Help me in rectifying the issue.
Note: I dont have code for AddProduct link but I think there will be no issues.
Code for View:
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage<MVCProductDetailsDemo.Models.ProductModel>" %>
<!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 runat="server">
<title>ProductDetails</title>
</head>
<body>
<div>
<% using(Html.BeginForm()){ %>
pid:<%=Html.TextBox("tbPid") %>
<%=Html.ActionLink("Search Product", "SearchProducts", "Product")%><br />
<%if (Model != null)
{ %>
pname:<%=Html.TextBox("tbPname", Model.PName)%><br />
Minqty:<%=Html.TextBox("tbMinQty",Model.MinOrdQty) %><br />
Maxqty:<%=Html.TextBox("tbMaxQty",Model.MaxOrdQty) %><br />
Up:<%=Html.TextBox("tbUP",Model.UnitPrice) %><br />
<%} %>
<%else { %>
Pname:<%=Html.TextBox("tbPname") %>
MinQty:<%= Html.TextBox("tbMinQty")%>
MaxQty:<%=Html.TextBox("tbMaxQty")%>
UP:<%=Html.TextBox("tbUP") %>
<%} %>
Manifacturer:<%=Html.DropDownList("manifacturers") %><br />
<%=Html.ActionLink("Add Product","AddProduct","Product") %>
<%=Html.ActionLink("Upd Product","UpdateProduct","Product") %>
<%=Html.ActionLink("Del Product","DeleteProduct","Product") %>
<%} %>
</div>
</body>
</html>
**Code for Controller:**
namespace MVCProductDetailsDemo.Controllers
{
public class ProductController : Controller
{
//Normal Methods and ActionMethods.
//ActionMethods are the methods which will usually call the views.
public ActionResult DisplayProduct()
{
List<string> lstManifacturers=GetManifacturers();
ViewData["manifacturers"] = new SelectList(lstManifacturers);
return View("ProductDetails");
}
public List<string> GetManifacturers()
{
Manifacturers manifacturer = new Manifacturers();
return manifacturer.GetManifacturers();
}
public ActionResult SearchProducts()
{
string pid=Request.Form["tbPid"];
Products products = new Products();
ProductModel pModel=products.GetProductDetails(Convert.ToInt32(pid));
List<string> lstManifacturers = GetManifacturers();
ViewData["manifacturers"] = new SelectList(lstManifacturers);
return View("ProductDetails", pModel);
}
public ActionResult UpdateProduct()
{
string pid = Request.Form["tbPid"];
string pname = Request.Form["tbPname"];
string minqty = Request.Form["tbMinQty"];
string maxqty = Request.Form["tbMaxQty"];
string up = Request.Form["tbUP"];
Products products = new Products();
ProductModel pModel = new ProductModel();
pModel.Mid = 1;
pModel.PName = pname;
pModel.MinOrdQty = Convert.ToInt32(minqty);
pModel.MaxOrdQty = Convert.ToInt32(maxqty);
pModel.Pid = Convert.ToInt32(pid);
pModel.UnitPrice = Convert.ToInt32(up);
bool isRecordUpdated = products.UpdateProducts(pModel);
List<string> lstManifacturers = GetManifacturers();
ViewData["manifacturers"] = new SelectList(lstManifacturers);
return View("ProductDetails", pModel);
}
public ActionResult DeleteProduct()
{
string pid = Request.Form["tbPid"];
Products products = new Products();
bool isRecordDeleted = products.DeleteProduct(Convert.ToInt32(pid));
List<string> lstManifacturers = GetManifacturers();
ViewData["manifacturers"] = new SelectList(lstManifacturers);
return View("ProductDetails");
}
}
}
Html.ActionLink produces anchor (a) tag that, when clicked, simply points the browser to a different address. What you need is a submit button that causes form data to be posted to the server. The url where form data is submitted can be controlled by the parameters of Html.BeginForm - during view rendering, or by javascript on the client as the value of action attribute of the form tag. If you don't specify Html.BeginForm paremeters (as in your code), the form will be posted to controller action with the same name as the one that produced the page. You need to create an overloaded action method (with parameter FormCollection collection, for example) and mark it with [HttpPost] attribute.

how I can read a from taglib to <% ... %>

could you help please?, how I can read the variable objd in a <% ... %> Assigned in the foreach?
<c:forEach var="objd" items="${beanDreqproducto}">
<%
Gson j = new Gson();
String data = j.toJson(objd);
%>
console.log("${objd.cantidad}, data: "+'${data}');
</c:forEach>
The ${} basically translates to PageContext#findAttribute(). So, this should do:
<%
Object objd = pageContext.findAttribute("objd");
// ...
%>
Note that you should set data in page scope as well in order to get ${data} to work:
<%
// ...
pageContext.setAttribute("data", data);
%>
See also:
Our EL wiki page
Unrelated to the concrete question, this approach is ultimately bad. You should choose to use either JSTL/EL or scriptlets exclusively, not both. If you prefer JSTL/EL, just create a custom EL function to do the desired job, so that you can end up something like as follows:
<c:forEach var="objd" items="${beanDreqproducto}">
console.log("${objd.cantidad}, data: ${my:toJson(objd)}");
</c:forEach>
Our EL wiki page contains a section how to create EL functions.