2011-07-07 63 views
0

如何使用MVC3編輯器模板進行添加和刪除列表?如何使用MVC3編輯器模板進行添加和刪除Razor viewengine的列表?

我有一個對象:

public class Policy 
{ 
    public List<PolicyLine> PolicyLines = new List<PolicyLine>(); 
} 

public class PolicyLine 
{ 
    public PolicyLine(bool isPositive, string policyText) 
    { 
     IsPositive = isPositive; 
     PolicyText = policyText; 
    } 

    public bool IsPositive { get; set; } 

    public string PolicyText { get; set; } 
} 

我有一個editorTemplate:在視圖\共享\ EditorTemplates \ Policy.cshtml和視圖\共享\ EditorTemplates \ PolicyLine.cshmtml,我想知道如何讓用戶從策略添加和刪除PolicyLines?

回答

1

我得到這個工作對我來說:

這裏是我的意見/政策/ Index.cshtml

@using (Html.BeginForm("Submit", "Policy")) { 
<fieldset> 
@Html.EditorForModel() 
</fieldset> 
} 

這裏是我的意見/共享/ EditorTemplates/Policy.cshtml

@model Policy 
<br /> 
<label for="IsPositive">Is positive?</label> 
@Html.CheckBox("IsPositive") 
<input type="text" name="PolicyText" /> 
<input type="submit" value="Add to Policy" title="SubmitFromReferalPolicy" /> 
@Html.EditorFor(a => a.PolicyLines) 

這是我的觀點/共享/編輯模板/ PolicyLine.cshtml

@model PolicyLine 
<br /> 
@this.Model.ToString() 
@Html.ActionLink("Delete", "DeleteLine/" + Model.Identifier.ToString()) 

這裏是我的Policy.cs

public class Policy 
{ 
    public string Id { get; set; } 

    public List<PolicyLine> PolicyLines = new List<PolicyLine>(); 

    public override string ToString() 
    { 
     return PolicyFormatter.FormatPolicy(this); 
    } 
} 

這裏是我的PolicyLine.cs

public class PolicyLine 
{ 
    public bool IsPositive { get; set; } 

    public string PolicyText { get; set; } 

    public Guid Identifier { get; set; } 

    public override string ToString() 
    { 
     return PolicyFormatter.FormatPolicyLine(this); 
    } 
} 

這裏是PolicyController.cs我add方法

[HttpPost] 
    public ActionResult Submit(PolicyLine submitted) 
    { 
     Policy saveMe = Policy.GetPolicyFromUserName(UserName); 
     submitted.Identifier = Guid.NewGuid(); 
     saveMe.PolicyLines.Add(submitted); 
     Store.Write(saveMe); 

     return RedirectToAction("Index"); 
    } 

這裏是我的刪除方法from PolicyController.cs

public ActionResult DeleteLine(Guid identifier) 
    { 
     Policy saveMe = Policy.GetPolicyFromUserName(UserName); 
     PolicyLine removeMe = saveMe.PolicyLines.Find(p => p.Identifier == identifier); 
     saveMe.PolicyLines.Remove(removeMe); 
     Store.Write(saveMe); 
     return RedirectToAction("Index"); 
    } 
1

對於DELETE,只需將以下行添加到PolicyLine.cshtml並添加一個刪除操作到您的控制器來執行刪除。

@Html.ActionLink("Delete", "Delete", new { id = @Model.PolicyID }) 

的ADD是有點麻煩,你可以添加按鈕,您Policy.cshtml,然後調用一些JavaScript插入一些HTML的飛行。 或 您可以讓該按鈕顯示一個新頁面來捕獲新的policyline,然後返回到添加了新行的原始頁面。

相關問題