public ActionResult AddNew()
{
CreateEmployeeViewModel vm = new CreateEmployeeViewModel();
vm.FirstName = "FirstName";
vm.LastName = "LastName";
vm.Salary = "0";
return View("CreateEmployee", vm);
//return View("CreateEmployee");
}
public ActionResult SaveEmployee(Employee e, string BtnSubmit)
{
switch (BtnSubmit)
{
case "Save Employee":
if (ModelState.IsValid)
{
EmployeeBusinessLayer empBal = new EmployeeBusinessLayer();
empBal.SaveEmployee(e);
return RedirectToAction("GetEmployeeListView");
}
else
{
CreateEmployeeViewModel vm = new CreateEmployeeViewModel();
vm.FirstName = e.FirstName;
vm.LastName = e.LastName;
if (e.Salary!=null)
{
vm.Salary = e.Salary.ToString();
}
else
{
vm.Salary = ModelState["Salary"].Value.AttemptedValue;
}
return View("CreateEmployee", vm); // Day 4 Change - Passing e here
}
case "Cancel":
return RedirectToAction("GetEmployeeListView");
}
return new EmptyResult();
}
public class CreateEmployeeViewModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Salary { get; set; }
}
public class Employee
{
[Key]
public int EmployeeId { get; set; }
[FirstNameValidation]
public string FirstName { get; set; }
[StringLength(5,ErrorMessage="Last Name length should not be greater than 5")]
public string LastName { get; set; }
[Required(ErrorMessage = "the Salary field is required!")]
public int Salary { get; set; }
}
@using MvcAppLesson2.Models
@model CreateEmployeeViewModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>CreateEmployee</title>
<script>
function ResetForm() {
document.getElementById('TxtFName').value = "";
document.getElementById('TxtLName').value = "";
document.getElementById('TxtSalary').value = "";
}
</script>
</head>
<body>
<hr />
SaveEmployee:<br />
<div>
<form action="/Employee/SaveEmployee" method="post">
<table>
<tr>
<td>
First Name:
</td>
<td>
<input type="text" id="TxtFName" name="FirstName" value="@Model.FirstName" />
</td>
</tr>
<tr>
<td colspan="2" align="right">
@Html.ValidationMessage("FirstName")
</td>
</tr>
<tr>
<td>
Last Name:
</td>
<td>
<input type="text" id="TxtLName" name="LastName" value="@Model.LastName" />
</td>
</tr>
<tr>
<td colspan="2" align="right">
@Html.ValidationMessage("LastName")
</td>
</tr>
<tr>
<td>
Salary:
</td>
<td>
<input type="text" id="TxtSalary" name="Salary" value="@Model.Salary" />
</td>
</tr>
<tr>
<td colspan="2" align="right">
@Html.ValidationMessage("Salary")
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="BtnSubmit" value="Save Employee" />
<input type="submit" name="BtnSubmit" value="Cancel" />
<input type="button" name="BtnReset" value="Reset" onclick="ResetForm();" />
</td>
</tr>
</table>
</form>
</div>
<hr />
</body>
</html>