In this article we are going to see the various ways of accessing a values from the view form post in the
action.
HTML :
FormCollection:
From this FormCollection developer can get the all controls values present with in the form while post.Values are stored as key/values pairs
Parameter:
From This method all the elements are mention as parameter with the same name as the control name to the input for action then it is default mapped the values to that variable, parameters can be in any order.
Output:
From this article you can learn the various ways of access a values from the request posted from the client.
action.
HTML :
@model TestingMvc.Models.Employee
@{
ViewBag.Title = "Create
Employee";
}
<h2>
Create Employee</h2>
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<fieldset style="width:300px">
<legend>Employee</legend>
<br />
<div class="editor-label">
@Html.LabelFor(m => m.EmployeeName)
</div>
<div class="editor-field">
@Html.EditorFor(m => m.EmployeeName)
@Html.ValidationMessageFor(m=>m.EmployeeName)
</div>
<div class="editor-label">
@Html.LabelFor(x => x.Country)
</div>
<div class="editor-field">
@Html.EditorFor(x => x.Country)
@Html.ValidationMessageFor(x=>x.Country)
</div>
<div class="editor-label">
@Html.LabelFor(x => x.DepartmentId, "Department")
</div>
<div class="editor-field">
@Html.DropDownList("Departments",
new List<SelectListItem>(){
new SelectListItem(){Text="TECH",Value="1"},
new SelectListItem(){Text="HR",Value="2"},
new SelectListItem(){Text="Finance",Value="3"}
}, "Select
Department")
@Html.ValidationMessageFor(x=>x.DepartmentId)
</div>
<div class="editor-label">
@Html.LabelFor(x=>x.Married)
</div>
<div class="editor-field">
@Html.DropDownList("Married",new List<SelectListItem>(){
new SelectListItem(){Text="Yes",Value="YES"},
new SelectListItem(){Text="No",Value="NO"}
})
@Html.ValidationMessageFor(x=>x.Married)
</div>
<br />
<input type="submit" value="Create" />
</fieldset>
}
<br />
@Html.ActionLink("Back
to List","Index","Department")FormCollection:
From this FormCollection developer can get the all controls values present with in the form while post.Values are stored as key/values pairs
[HttpPost]
public ActionResult
Create(FormCollection form)
{
BusLayer bl = new BusLayer();
bl.Create(form["EmployeeName"],
form["Country"], form["Married"], int.Parse(form["Departments"]));
return RedirectToAction("Details",
new { id=int.Parse(form["Departments"])});
}
From This method all the elements are mention as parameter with the same name as the control name to the input for action then it is default mapped the values to that variable, parameters can be in any order.
[HttpPost]
public ActionResult
Create(string employeename,string country,string
married,int departments)
{
BusLayer bl = new BusLayer();
bl.Create(employeename,country,married,departments);
return RedirectToAction("Details",
new { id=departments});
}