簡體   English   中英

是否可以從XDocument XElement調用操作?

[英]Is it possible to call an action from an XDocument XElement?

我正在使用.NET Core中的XDocument生成日歷,並將其作為標記幫助程序傳遞給視圖。

我想讓每一天都可以點擊並將每天的日期作為Id傳遞給另一個控制器中的動作。 這是可以使用XDocument還是只能生成原始HTML?

理想情況下我想做的事情是這樣: @Html.ActionLink("", "ActionName", "ControllerName", new { date = d })每天。

我已經嘗試用<a> XAttribute將<div>class="day"包裝在一起,其中dhref - 這使得日期可點擊並在URL中傳遞DateTime但我無法確定如何調用特定的行動。

var startDate = monthStart.AddDays(-(int)monthStart.DayOfWeek);
var dates = Enumerable.Range(0, 42).Select(i => startDate.AddDays(i));

foreach (var d in dates)
{
    if (d.DayOfWeek == DayOfWeek.Sunday && d != startDate)
    {
        yield return new XElement("div",
            new XAttribute("class", "w-100"),
            String.Empty
        );
    }

    var mutedClasses = "d-none d-inline-block bg-light text-muted";
    yield return new XElement("div",
        new XAttribute("class", $"day col p-2 border-top-0 text-truncate {(d.Month != monthStart.Month ? mutedClasses : null)}"),
        new XElement("h6",
            new XAttribute("class", "row align-items-center"),
            new XElement("span",
                new XAttribute("class", "date col-1"),
                d.Day
            ),
            new XElement("span",
                new XAttribute("class", "col-1"),
                String.Empty
            )
        ),
        GetEventHtml(d)
    );
}

假設此代碼在控制器中,您可以通過調用controllerbase的Url屬性來設置錨點的href(實現IUrlHelper)

例如:new XAttribute(“href”,Url(“ActionName”,“ControllerName”,new {date = d}))

我能夠通過使用LinkGenerator實現這一目標

public class CalendarTagHelper : TagHelper
{
    private readonly LinkGenerator _linkGenerator;

    public CalendarTagHelper(LinkGenerator linkGenerator)
    {
        _linkGenerator = linkGenerator;
    } 

然后在傳遞d作為參數a XElement的href中調用此方法:

    private string GetDayUrl(DateTime date)
    {
        return _linkGenerator.GetPathByAction("Day", "Home", values: {date = date});
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM