How to access posted form data in action method and display in view
I’m creating an input wizard in MVC. There are two views, one for taking input from user and another for display the input data.
Here is the model’s code:
public class Info
{
public int CustomerId { set; get; }
public double Price { set; get; }
public string name { set; get; }
}
}
Controller’s Code-
public ActionResult FillCustomer()
{
return View();
}
public ActionResult DisplayCustomer(FormCollection frm)
{
Info info = new Info();
info.name = Convert.ToString( Request.Form["name"]);
info.Price = Convert.ToDouble(Request.Form["price"]);
info.CustomerId = Convert.ToInt32(Request.Form["customerid"]);
return View(info);
}
FillCustomer View’s Code-
<form method="post" action="DisplayCustomer">
Name: <input type="text" id="name" /><br />
Price: <input type="text" id="price" /><br />
CustomerId: <input type="text" id="customerid" />
<br />
<input type="submit" id="btn1" />
</form>
</body>
</html>
DisplayCustomer View’s Code-
<body>
<div>
Name is <%=Model.name %> and ID is <%=Model.CustomerId %>
<%if (Model.Price > 200)
{%>
Greater than 200
<%}
else %>
<%{%>Lesser than 200
<%} %>
</div>
</body>
</html>
I checked with debugger, controller is not getting posted data.
Your form’s input elements should have a name attribute
Now you will get form data as
In controller, form data is received as key/value pairs. And keys are generaetd from name attributes.