카테고리 보관물: c#

c#

HTML.ActionLink 메소드 public ActionResult Login(int id) 어떻게 하는건가요?

아래와 같은 코드가 있다고 가정 해 봅시다

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
);

답변

조셉 킹 리의 대답에 덧붙이고 싶었습니다 . 그는 해결책을 제공했지만 처음에는 해결책을 얻지 못했고 Adhip Gupta와 같은 결과를 얻었습니다. 그런 다음 경로가 먼저 존재해야하며 매개 변수가 경로와 정확하게 일치해야한다는 것을 깨달았습니다. 그래서 나는 내 경로에 대한 ID와 텍스트 매개 변수를 가지고 있었고 포함해야했습니다.

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

답변

이 방법을 RouteLink()사용하면 사전을 통해 모든 것을 지정할 수 있습니다 (링크 텍스트 및 경로 이름 제외).


답변

나는 조셉이 컨트롤러와 행동을 뒤집 었다고 생각합니다. 먼저 동작 다음에 컨트롤러가옵니다. 이것은 다소 이상하지만 서명이 보이는 방식입니다.

명확히하기 위해, 이것은 작동하는 버전입니다 (Joseph의 예의 적응) :

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<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 ValuesHTML Attributes에 대한 두 가지 재정의가 포함되며 , 모든보기에 추가해야 @using YourProject.Controllers합니다.web.config <pages><namespaces>