【问题标题】:Error in looking for Action with Parameters from View upon submit提交时从视图中查找带有参数的操作时出错
【发布时间】:2011-02-24 07:45:39
【问题描述】:

我有以下代码,我很惊讶它给了我错误消息:

没有为此对象定义无参数构造函数。

  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);
        }
    }
public ActionResult Tasks(int ID, string Name)
    {
        EmployeeListModel model = new EmployeeListModel(ID, projectName);
        return View(model);
    }

查看 CreateEmployee:

    @model MvcUI.Models.Employee

@using (Html.BeginForm())
{
@Html.Partial("EmpDetails", Model)
 <p>  <input type="submit" value="Save" /></p> 
}

【问题讨论】:

    标签: asp.net asp.net-mvc asp.net-mvc-3


    【解决方案1】:

    这很正常。看起来 Employee 对象没有无参数构造函数,但您在 POST 操作中将其用作操作参数:

    public ActionResult CreateEmployee(Employee model)
    

    默认模型绑定器被调用以从 POST 请求值绑定 Employee 对象,它不可能知道如何实例化它。您可以为此对象提供无参数构造函数,也可以编写自定义模型绑定器。

    【讨论】:

      【解决方案2】:

      看起来您的Employee 类没有定义无参数构造函数。你应该定义一个无参数的构造函数

      public class Employee {
      
        //parameterless constructor
        public Employee() {
      
        }
      
        //your constructor
        public Employee(int id, string name) {
      
        }
      
      }
      

      默认模型绑定器使用无参数构造函数在CurrentEmployee 操作中实例化您的对象。否则它将不知道如何实例化您的对象。

      或者,您可以创建一个自定义模型绑定器来创建和绑定您的 Employee 对象。

      【讨论】:

        猜你喜欢
        • 2011-12-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-20
        • 2023-03-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多