2012-12-29 53 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

相關問題