2012-12-29 63 views
-4

我正在开发一个项目,但我不习惯C#。我试图按照旧的工作代码工作。我找不到任何区别。没有无参数的构造函数为这个对象定义,ID为

我的HTML表单:

@using (Html.BeginForm()) 
{ 
    @Html.ValidationSummary(true) 
    @Html.HiddenFor(model => model.TicketID) 
    <fieldset> 
     <legend>Ticketdetail</legend> 

      <div class="editor-label"> 
      @Html.LabelFor(model => model.Anmerkung) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.Anmerkung) 
      @Html.ValidationMessageFor(model => model.Anmerkung) 
     </div> 

     <p> 
      <input type="submit" value="Create" /> 
     </p> 
    </fieldset> 
} 

行动:

public ActionResult CreateDetail(int id) 
{ 
    if (id == -1) return Index(-1); 
    return View(new cTicketDetail(id, User.Identity.Name)); 
} 

[HttpPost] 
public ActionResult CreateDetail(cTicketDetail collection) 
{ 


    //int TicketID = collection.TicketID; 
    try 
    { 
     if (ModelState.IsValid) 
     { 
      collection.Write(); 
     } 
     return RedirectToAction("Details", collection.TicketID); 
    } 
    catch 
    { 
     return this.CreateDetail(collection.TicketID); 
    } 
} 

the error after commiting my Form

回答

1

看起来你已经在你的CreateDetail动作中使用不具有无参数的cTicketDetail类型构造函数。控制器操作不能将参数类型作为参数,因为默认模型联编程序不知道如何实例化它们。

这里的最佳做法是定义视图模型,然后让您的控制器操作将此视图模型作为参数,而不是使用您的域实体。

如果你不想使用视图模型,你将不得不修改cTicketDetail类型,以便它有一个默认的构造函数:

public class cTicketDetail 
{ 
    // The default parameterless constructor is required if you want 
    // to use this type as an action argument 
    public cTicketDetail() 
    { 
    } 

    public cTicketDetail(int id, string username) 
    { 
     this.Id = id; 
     this.UserName = username; 
    } 

    public int Id { get; set; } 
    public string UserName { get; set; } 
} 
+0

哇THX!我认为这将是okey,因为它就像公共cTicketDetail(INT ID = -1,字符串用户名=“”),但现在它可以与一个额外的结构 – yellowsir

相关问题