如何使用Razor viewengine添加和删除列表的MVC3编辑器模板?

时间:2011-07-07 12:48:51

标签: asp.net-mvc-3 razor

如何使用添加和删除列表的MVC3编辑器模板?

我有一个对象:

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:在Views \ Shared \ EditorTemplates \ Policy.cshtml和Views \ Shared \ EditorTemplates \ PolicyLine.cshmtml中,我想知道如何让用户在策略中添加和删除PolicyLines?

2 个答案:

答案 0 :(得分:1)

对于DELETE,只需将以下行添加到PolicyLine.cshtml中,并向Controller添加删除操作以执行删除。

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

ADD有点棘手,您可以向Policy.cshtml添加按钮,然后调用一些javascript来动态插入一些html。 要么 您可以让按钮显示一个新页面以捕获新的policyline,然后返回到添加了新行的原始页面。

答案 1 :(得分:1)

我让这个为我工作:

这是我的观点/政策/ Index.cshtml

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

这是我的Views / Shared / 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)

这是我的Views / Shared / EditorTemplates / 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中添加的方法

    [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");
    }

这是我在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");
    }