Retrieving Form collection data from action methods using mvc 2.0 - html

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.

Related

button click in html for jsp

I have the following coding in JSP which work when a JSP page is loaded:
<%
String sportugues = request.getParameter("port");
String senglish = request.getParameter("engl");
String sfuncgram = request.getParameter("funcgram");
//Integer snsyn = Integer.valueOf(request.getParameter("nsyninp"));
Usuario usu = new Usuario();
usu.setPortugues(sportugues);
usu.setEnglish(senglish);
usu.setFuncgram(sfuncgram);
//usu.setNsyn(snsyn);
UsuarioDao usudDao = new UsuarioDao();
usudDao.cadastroStudyAlfaDireita(usu);
%>
But I want it to work only when I click a HTML button like:
<button onclick="">JSP Command</button>
The button and the JSP coding must be in the same JSP page.
You can wrap your code that you need to load when click in a condition that check isButtonClick, then assign to onClick a function to update it
<c:set var="isButtonClicked" value="false" />
<c:if test="${isButtonClicked}">
<%
String sportugues = request.getParameter("port");
String senglish = request.getParameter("engl");
String sfuncgram = request.getParameter("funcgram");
//Integer snsyn = Integer.valueOf(request.getParameter("nsyninp"));
Usuario usu = new Usuario();
usu.setPortugues(sportugues);
usu.setEnglish(senglish);
usu.setFuncgram(sfuncgram);
//usu.setNsyn(snsyn);
UsuarioDao usudDao = new UsuarioDao();
usudDao.cadastroStudyAlfaDireita(usu);
%>
</c:if>
<button onClick="function(){<c:set var="isButtonClicked" value="${!isButtonClicked}"} />

ASP.NET MVC HtmlTagBuilder dosen't work

I tried to extend the HtmlHelper by a paragraph element this is the Code:
<Extension()>
Public Function Para(ByRef helper As HtmlHelper) As String
Dim builder = New TagBuilder("p")
builder.SetInnerText("Hello World")
Return builder.ToString()
End Function
View:
#ModelType BookViewModel
#Code
ViewData("Title") = "Index"
End Code
#Using (Ajax.Form("Index", "BooksController", "BookList", "ajax_form"))
#<input type = "search" name="search" id="search" />
#<input type = "submit" value="Filter" />
End Using
#Html.Para()
#Html.Partial("_Books", Model)
It produces the following Output on the page:
<p> Hello World </p>
instead of only Hello World.
Why isn't this working.

to send value of <input> tag dynamically through iteration

this is my code:
<%#page import="java.sql.Connection"%>
<%#page import="java.sql.Statement"%>
<%#page import="java.sql.ResultSet"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%
//String b1=request.getParameter("b1");
String fy=request.getParameter("fy1");
Connection con=conn.connectionprovider.getDbConnection();
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from institutemaster where fy='"+fy+"'");
out.println("<form action=adminlistvalidate method=post ><table border='3'>");
out.println("<tr><th>FINANCIAL YEAR</th><th>INSTITUTE ID</th><th>INSTITUTE NAME</th><th></th><th></th></tr>");
**while (rs.next())
{%>
<% out.println("<tr><td>"+rs.getString(1)+"</td><td>"+rs.getInt(2)+"</td><td>"+rs.getString(3)+"</td><td>active <input type=radio checked=checked name="+rs.getInt(2)+" value=a /> </td><td>inactive<input type=radio name="+rs.getInt(2)+" value=b /></td></tr>"); %>**
<% }//request.setAttribute("name",rs.getInt(2));
out.println("</table><input type=submit name=submit value=submit />");
out.println("</form>");
%>
now see the highlighted part. im sending each row of table obtained to next servlet page using dynamic name . i actually want to make an admin page in which admin can activate or deactivate intitutes at his will. so each active and inactive radio button has a name obtained from the database ie. a dynamic name.
my next servlet page is:
try {
Connection con=conn.connectionprovider.getDbConnection();
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from institutemaster");
//out.println("tom");
while(rs.next())
{
// out.print(" cat");
**if( request.getParameter(rs.getInt(2)+"").equals("a") )
{
int rs1=st.executeUpdate("update institutemaster set status='active' where instid="+rs.getInt(2)+"");
out.print("status=active");
}
else
{
int rs1=st.executeUpdate("update institutemaster set status='inactive' where instid="+rs.getInt(2)+"");
out.print("status=inactive");
}**
}
//out.print("done");
}
catch(Exception e){}
now in this , i am able to recieve and compare only the 1st radio button value
(see the highlighted area). it means that the only the first value through iteration is being sent from last page n other values are not.
any help please?

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

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"];
}

returning data from checkboxes in mvc 2 view

I'm using checkboxes in the view of my MVC2 project to allow users to select multiple objects. Here is the code in my view(skipping unrelated lines:
<h2>Install New Equipment</h2>
//Html.BeginForm("CreateRequest1", "Home", FormMethod.Post);
<div>Employee's First Name: <%= Model.Employee.EmpFName%></div>
<div>Employee's Last Name: <%= Model.Employee.EmpLName%></div>
<div>Employee's Phone Number: <%= Model.Employee.Phone%> </div>
<br />
<div>Please select the equipment you would like to request:</div><br />
<div> <% foreach (var info in ViewData.Model.EquipDescription)
{ %>
<% = Html.CheckBox("Description", info.ID) %><%=info.Description%> <br />
<%} %>
</div><br />
<div>Please Select the Location for the Equipment to be Installed </div><br />
<div>Building <%= Html.DropDownList("NewBuildings", new SelectList((IEnumerable)ViewData["buildings"], "ID", "Buildings")) %>
Floor <%= Html.DropDownList("NewFloors", new SelectList((IEnumerable)ViewData["floors"], "ID", "FloorNumber")) %>
Office<%= Html.DropDownList("NewOffices", new SelectList((IEnumerable)ViewData["offices"], "ID", "OfficeNumber")) %>
</div>
<br />
<div>Comments: <%=Html.TextArea("Comments") %></div><br />
<%Html.EndForm(); %>
(I removed the <%%> around the begin form line so my whole post would show)
Everything display perfectly in the view. I recieve all the other data from the user. I just don't know how to recieve the data from the selected checkboxes
[HttpPost]
public ActionResult CreateRequest1(int NewBuildings, int NewFloors, int NewOffices, string comments, int[] Description)
What should I add here to get the selected values?
You'll need to add a parameter to your method like:
[HttpPost]
public ActionResult CreateRequest1(int NewBuildings, int NewFloors, int NewOffices, string comments, ICollection Description)
I assume your value is an int, but you can change it if required.
You can read more here:
http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx