Error in looking for Action with Parameters from View upon submit
I am having the following piece of code and i'm surprised that it's giving me error message:
No parameterless constructor defined for this object.
public ActionResult CreateEmployee(int ID, string Name)
{
Employee model = new Employee(ID, Name);
return View(model);
}
[HttpPost]
public ActionResult CreateEmployee(Employee model)
{
try
{
return RedirectToAction("Tasks");
}
catch (Exception e)
{
ModelState.AddModelError("Error", e.Message);
return View(model);
开发者_StackOverflow社区 }
}
public ActionResult Tasks(int ID, string Name)
{
EmployeeListModel model = new EmployeeListModel(ID, projectName);
return View(model);
}
View for CreateEmployee:
@model MvcUI.Models.Employee
@using (Html.BeginForm())
{
@Html.Partial("EmpDetails", Model)
<p> <input type="submit" value="Save" /></p>
}
That's normal. It looks like the Employee object doesn't have a parameterless constructor and yet you are using it as action parameter in your POST action:
public ActionResult CreateEmployee(Employee model)
The default model binder which is invoked to bind the Employee object from the POSTed request values cannot possibly know how to instantiate it. You could either provide a parameterless constructor to this object or write a custom model binder.
It looks like your Employee
class doesn't have a parameterless constructor defined. You should define a parameterless constructor
public class Employee {
//parameterless constructor
public Employee() {
}
//your constructor
public Employee(int id, string name) {
}
}
The default model binder uses the parameterless constructor to instantiate your object in the CurrentEmployee
action. Otherwise it wouldn't know how to instantiate your object.
Alternatively you could create a custom model binder to create and bind your Employee
object.
精彩评论