Trabajando con Formularios
Creamos un archivo Form.cshtml
<!DOCTYPE html>
<html>
<head>
<title>Customer Form</title>
</head>
<body>
<form method=”post” action=”">
<fieldset>
<legend>Add Customer</legend>
<div>
<label for=”CompanyName”>Company Name:</label>
<input type=”text” name=”CompanyName” value=”" />
</div>
<div>
<label for=”ContactName”>Contact Name:</label>
<input type=”text” name=”ContactName” value=”" />
</div>
<div>
<label for=”Employees”>Employee Count:</label>
<input type=”text” name=”Employees” value=”" />
</div>
<div>
<label> </label>
<input type=”submit” value=”Submit” />
</div>
</fieldset>
</form>
</body>
</html>
1.- Leer entrada de usuario desde Form
Al principio de Form colocamos
@{
if (IsPost) {
string companyname = Request["companyname"];
string contactname = Request["contactname"];
int employeecount = Request["employees"].AsInt();
<text>
You entered: <br />
Company Name: @companyname <br />
Contact Name: @contactname <br />
Employee Count: @employeecount <br />
</text>
}
}
2.- Validar entrada de usuario
En form reemplazamos el código inicial por:
@{
if (IsPost) {
var errors = false;
var companyname = Request["companyname"];
if (companyname.IsEmpty()) {
errors = true;
@:Company name is required.<br />
}
var contactname = Request["contactname"];
if (contactname.IsEmpty()) {
errors = true;
@:Contact name is required.<br />
}
var employeecount = 0;
if (Request["employees"].IsInt()) {
employeecount = Request["employees"].AsInt();
} else {
errors = true;
@:Employee count must be a number.<br />
}
if (errors == false) {
<text>
You entered: <br />
Company Name: @companyname <br />
Contact Name: @contactname <br />
Employee Count: @employeecount <br />
</text>
} }
}
3.- Restaura Valores de Formulario después de PostBack
<!DOCTYPE html>
<html>
<head>
<title>Customer Form</title>
</head>
<body>
<form method=”post” action=”">
<fieldset>
<legend>Add Customer</legend>
<div>
<label for=”CompanyName”>Company Name:</label>
<input type=”text” name=”CompanyName”
value=”@Request["companyname"]” />
</div>
<div>
<label for=”ContactName”>Contact Name:</label>
<input type=”text” name=”ContactName”
value=”@Request["contactname"]” />
</div>
<div>
<label for=”Employees”>Employee Count:</label>
<input type=”text” name=”Employees” value=”@Request["employees"]” />
</div>
<div>
<label> </label>
<input type=”submit” value=”Submit” />
</div>
</fieldset>
</form>
</body>
</html>

agosto 28th, 2011
admin
Posted in