HTML.ActionLink와
Url.Action` 사이에 차이가 있나요, 아니면 같은 일을 하는 두 가지 방법일 뿐인가요?
언제 어느 쪽을 더 선호해야 하나요?
네, 차이가 있습니다. 'Html.ActionLink는
<a href=<..>../a>태그를 생성하는 반면
Url.Action`은 URL만 반환합니다.
예를 들어
@Html.ActionLink("link text", "someaction", "somecontroller", new { id = "123" }, null)
를 생성합니다:
<a href="/somecontroller/someaction/123">link text</a>
그리고 Url.Action("일부 액션;, "일부 컨트롤러;, 새로운 { id = "123" })
을 생성합니다:
/somecontroller/someaction/123
자식 컨트롤러 액션을 실행하는 Html.Action도 있습니다.
Html.ActionLink는
<a href=<..<...</a<` 태그를 자동으로 생성합니다.
Url.Action`은 URL만 생성합니다.
예를 들어
@Html.ActionLink("link text", "actionName", "controllerName", new { id = "<id>" }, null)
를 생성합니다:
<a href="/controllerName/actionName/<id>">link text</a>
및
@Url.Action("actionName", "controllerName", new { id = "<id>" })
를 생성합니다:
/controllerName/actionName/<id>
제가 좋아하는 가장 좋은 점은 Url.Action(...)
을 사용하는 것입니다.
앵커 태그를 직접 만들어서 다른 HTML 태그를 사용해도 쉽게 링크 텍스트를 설정할 수 있다는 점입니다.
<a href="@Url.Action("actionName", "controllerName", new { id = "<id>" })">
<img src="<ImageUrl>" style"width:<somewidth>;height:<someheight> />
@Html.DisplayFor(model => model.<SomeModelField>)
</a>
<p>
@Html.ActionLink("Create New", "Create")
</p>
@using (Html.BeginForm("Index", "Company", FormMethod.Get))
{
<p>
Find by Name: @Html.TextBox("SearchString", ViewBag.CurrentFilter as string)
<input type="submit" value="Search" />
<input type="button" value="Clear" onclick="location.href='@Url.Action("Index","Company")'"/>
</p>
}
위의 예에서 특정 작업을 수행하기 위해 특별히 버튼이 필요한 경우 @Url.Action을 사용해야 하는 반면, 링크만 필요한 경우 @Html.ActionLink를 사용한다는 것을 알 수 있습니다. 중요한 것은 어떤 요소(HTML)에 액션 URL을 사용해야 할 때입니다.
html 태그를 @HTML.ActionLink '는' a '앵커'. 'A' 동시에 '는' @Url.Action uirl 당신꺼에요. 이를 통해 쉽게 파악할 수 있습니다.
// 1. <a href="/ControllerName/ActionMethod">Item Definition</a>
@HTML.ActionLink("Item Definition", "ActionMethod", "ControllerName")
// 2. /ControllerName/ActionMethod
@Url.Action("ActionMethod", "ControllerName")
// 3. <a href="/ControllerName/ActionMethod">Item Definition</a>
<a href="@Url.Action("ActionMethod", "ControllerName")"> Item Definition</a>
이 두 가지 방식이 전혀 다른 또한 필요에 따라 달라집니다.