programing

HTML.ActionLink 메서드

mailnote 2023. 5. 11. 21:43
반응형

HTML.ActionLink 메서드

수업이 있다고 치자.

public class ItemController:Controller
{
    public ActionResult Login(int id)
    {
        return View("Hi", id);
    }
}

항목 폴더에 없는 페이지에서ItemController상주, 나는 링크를 만들고 싶습니다.Login방법.그래서 어느것이Html.ActionLink사용해야 하는 방법과 어떤 매개 변수를 통과해야 합니까?

구체적으로, 저는 그 방법을 대체할 방법을 찾고 있습니다.

Html.ActionLink(article.Title,
    new { controller = "Articles", action = "Details",
          id = article.ArticleID })

최근 ASP에서 은퇴했습니다.NET MVC 화신.

당신이 원하는 것은 다음과 같습니다.

ASP.NET MVC1

Html.ActionLink(article.Title, 
                "Login",  // <-- Controller Name.
                "Item",   // <-- ActionMethod
                new { id = article.ArticleID }, // <-- Route arguments.
                null  // <-- htmlArguments .. which are none. You need this value
                      //     otherwise you call the WRONG method ...
                      //     (refer to comments, below).
                )

이것은 다음 방법의 ActionLink 서명을 사용합니다.

public static string ActionLink(this HtmlHelper htmlHelper, 
                                string linkText,
                                string controllerName,
                                string actionName,
                                object values, 
                                object htmlAttributes)

ASP.NET MVC2

두 가지 주장이 바뀌었습니다.

Html.ActionLink(article.Title, 
                "Item",   // <-- ActionMethod
                "Login",  // <-- Controller Name.
                new { id = article.ArticleID }, // <-- Route arguments.
                null  // <-- htmlArguments .. which are none. You need this value
                      //     otherwise you call the WRONG method ...
                      //     (refer to comments, below).
                )

이것은 다음 방법의 ActionLink 서명을 사용합니다.

public static string ActionLink(this HtmlHelper htmlHelper, 
                                string linkText,
                                string actionName,
                                string controllerName,
                                object values, 
                                object htmlAttributes)

ASP.NET MVC3+

인수는 MVC2와 동일한 순서이지만 id 값은 더 이상 필요하지 않습니다.

Html.ActionLink(article.Title, 
                "Item",   // <-- ActionMethod
                "Login",  // <-- Controller Name.
                new { article.ArticleID }, // <-- Route arguments.
                null  // <-- htmlArguments .. which are none. You need this value
                      //     otherwise you call the WRONG method ...
                      //     (refer to comments, below).
                )

이렇게 하면 라우팅 로직을 링크에 하드 코딩하지 않아도 됩니다.

 <a href="/Item/Login/5">Title</a> 

그러면 다음과 같은 html 출력이 제공됩니다.

  1. article.Title = "Title"
  2. article.ArticleID = 5
  3. 다음 경로가 여전히 정의되어 있습니다.

. .

routes.MapRoute(
    "Default",     // Route name
    "{controller}/{action}/{id}",                           // URL with parameters
    new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
);

저는 조셉 킹리의 대답에 추가하고 싶었습니다.그는 해결책을 제공했지만 처음에는 나도 그것을 작동시키지 못했고 아디프 굽타와 같은 결과를 얻었습니다.그리고 나서 저는 경로가 처음부터 존재해야 하고 매개변수가 경로와 정확히 일치해야 한다는 것을 깨달았습니다.그래서 저는 제 경로에 대한 ID와 텍스트 매개 변수를 가지고 있었고, 이 또한 포함되어야 했습니다.

Html.ActionLink(article.Title, "Login", "Item", new { id = article.ArticleID, title = article.Title }, null)

방법을 확인해 보는 것이 좋을 것입니다.그러면 사전을 통해 모든 항목(링크 텍스트 및 경로 이름 제외)을 지정할 수 있습니다.

저는 조셉이 조종사와 액션을 뒤집었다고 생각합니다.먼저 작업이 시작되고 그 다음에 컨트롤러가 시작됩니다.이것은 다소 이상하지만, 서명이 보이는 방식입니다.

일을 명확히 하기 위해, 이것이 작동하는 버전입니다(요셉의 예를 적용).

Html.ActionLink(article.Title, 
    "Login",  // <-- ActionMethod
    "Item",   // <-- Controller Name
    new { id = article.ArticleID }, // <-- Route arguments.
    null  // <-- htmlArguments .. which are none
    )

이것은 어떻습니까?

<%=Html.ActionLink("Get Involved", 
                   "Show", 
                   "Home", 
                   new 
                       { 
                           id = "GetInvolved" 
                       }, 
                   new { 
                           @class = "menuitem", 
                           id = "menu_getinvolved" 
                       }
                   )%>
Html.ActionLink(article.Title, "Login/" + article.ArticleID, 'Item") 

가독성과 혼동을 방지하기 위해 명명된 매개 변수를 사용합니다.

@Html.ActionLink(
            linkText: "Click Here",
            actionName: "Action",
            controllerName: "Home",
            routeValues: new { Identity = 2577 },
            htmlAttributes: null)

팬시팬츠를 즐기려면 다음과 같이 확장할 수 있습니다.

@(Html.ActionLink<ArticlesController>(x => x.Details(), article.Title, new { id = article.ArticleID }))

당신은 이것을 그것에 넣어야 할 것입니다.System.Web.Mvc네임스페이스:

public static class MyProjectExtensions
{
    public static MvcHtmlString ActionLink<TController>(this HtmlHelper htmlHelper, Expression<Action<TController>> expression, string linkText)
    {
        var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext, htmlHelper.RouteCollection);

        var link = new TagBuilder("a");

        string actionName = ExpressionHelper.GetExpressionText(expression);
        string controllerName = typeof(TController).Name.Replace("Controller", "");

        link.MergeAttribute("href", urlHelper.Action(actionName, controllerName));
        link.SetInnerText(linkText);

        return new MvcHtmlString(link.ToString());
    }

    public static MvcHtmlString ActionLink<TController, TAction>(this HtmlHelper htmlHelper, Expression<Action<TController, TAction>> expression, string linkText, object routeValues)
    {
        var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext, htmlHelper.RouteCollection);

        var link = new TagBuilder("a");

        string actionName = ExpressionHelper.GetExpressionText(expression);
        string controllerName = typeof(TController).Name.Replace("Controller", "");

        link.MergeAttribute("href", urlHelper.Action(actionName, controllerName, routeValues));
        link.SetInnerText(linkText);

        return new MvcHtmlString(link.ToString());
    }

    public static MvcHtmlString ActionLink<TController>(this HtmlHelper htmlHelper, Expression<Action<TController>> expression, string linkText, object routeValues, object htmlAttributes) where TController : Controller
    {
        var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext, htmlHelper.RouteCollection);

        var attributes = AnonymousObjectToKeyValue(htmlAttributes);

        var link = new TagBuilder("a");

        string actionName = ExpressionHelper.GetExpressionText(expression);
        string controllerName = typeof(TController).Name.Replace("Controller", "");

        link.MergeAttribute("href", urlHelper.Action(actionName, controllerName, routeValues));
        link.MergeAttributes(attributes, true);
        link.SetInnerText(linkText);

        return new MvcHtmlString(link.ToString());
    }

    private static Dictionary<string, object> AnonymousObjectToKeyValue(object anonymousObject)
    {
        var dictionary = new Dictionary<string, object>();

        if (anonymousObject == null) return dictionary;

        foreach (PropertyDescriptor propertyDescriptor in TypeDescriptor.GetProperties(anonymousObject))
        {
            dictionary.Add(propertyDescriptor.Name, propertyDescriptor.GetValue(anonymousObject));
        }

        return dictionary;
    }
}

여기에는 다음에 대한 두 가지 오버라이드가 포함됩니다.Route Values그리고.HTML Attributes또한 모든 보기에서 다음을 추가해야 합니다.@using YourProject.Controllers또는 당신은 그것을 당신의 것에 추가할 수 있습니다.web.config <pages><namespaces>

MVC5로 저는 이렇게 했고 그것은 100% 작동 코드입니다.

@Html.ActionLink(department.Name, "Index", "Employee", new { 
                            departmentId = department.DepartmentID }, null)

너희들은 여기서 아이디어를 얻을 수 있어,

이 유형의 용도:

@Html.ActionLink("메인 페이지", "색인", "홈")

MainPage : 텍스트 색인 이름 : Action View Home : Home Controller

기본 사용 작업 링크

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>_Layout</title>
    <link href="@Url.Content("~/Content/bootsrap.min.css")" rel="stylesheet" type="text/css" />
</head>
<body>
    <div class="container">
        <div class="col-md-12">
            <button class="btn btn-default" type="submit">@Html.ActionLink("AnaSayfa","Index","Home")</button>
            <button class="btn btn-default" type="submit">@Html.ActionLink("Hakkımızda", "Hakkimizda", "Home")</button>
            <button class="btn btn-default" type="submit">@Html.ActionLink("Iletişim", "Iletisim", "Home")</button>
        </div> 
        @RenderBody()
        <div class="col-md-12" style="height:200px;background-image:url(/img/footer.jpg)">

        </div>
    </div>
</body>
</html>

언급URL : https://stackoverflow.com/questions/200476/html-actionlink-method

반응형