program tip

ASP.NET MVC-컨트롤러에 매개 변수 전달

radiobox 2020. 8. 16. 20:04
반응형

ASP.NET MVC-컨트롤러에 매개 변수 전달


다음과 같은 작업 방법이있는 컨트롤러가 있습니다.

public class InventoryController : Controller
{
    public ActionResult ViewStockNext(int firstItem)
    {
        // Do some stuff
    }
}

그리고 그것을 실행하면 다음과 같은 오류가 발생합니다.

매개 변수 사전에 매개 변수 'firstItem'에 대한 'System.Int32'형식의 유효한 값이 없습니다. 매개 변수를 선택적으로 만들려면 해당 유형이 참조 유형이거나 Nullable 유형이어야합니다.

나는 한 지점에서 작동하고 매개 변수없이 기능을 시도하기로 결정했습니다. 컨트롤러가 영속적이지 않다는 것을 알게 된 나는 매개 변수를 다시 넣었는데, 이제 메소드를 호출 할 때 매개 변수를 인식하지 못합니다.

이 URL 구문을 사용하여 작업을 호출하고 있습니다.

http://localhost:2316/Inventory/ViewStockNext/11

이 오류가 발생하는 이유와이를 수정하기 위해 수행해야하는 작업에 대한 아이디어가 있습니까?

클래스에 정수를 사용하는 다른 메서드를 추가하려고 시도했지만 같은 이유로 실패합니다. 문자열을 취하는 것을 추가하려고 시도했으며 문자열이 null로 설정되었습니다. 매개 변수없이 하나를 추가하려고 시도했지만 제대로 작동하지만 물론 내 요구에 맞지 않습니다.


라우팅은의 라인을 따라 설정되어야합니다 {controller}/{action}/{firstItem}. 기본값으로 라우팅을두면 {controller}/{action}/{id}당신의 global.asax.cs파일, 당신은 전달해야합니다 id.

routes.MapRoute(
    "Inventory",
    "Inventory/{action}/{firstItem}",
    new { controller = "Inventory", action = "ListAll", firstItem = "" }
);

... 또는 그에 가까운 것.


firstItem을 id로 변경할 수 있으며 작동합니다.

global.asax에서 라우팅을 변경할 수 있습니다 (권장하지 않습니다)

그리고 아무도 이것을 언급하지 않았다는 것을 믿을 수 없습니다.

http://localhost:2316/Inventory/ViewStockNext?firstItem=11

@ Url.Action에서 다음과 같습니다.

@Url.Action("ViewStockNext", "Inventory", new {firstItem=11});

하는 일의 유형에 따라 마지막이 더 적합 할 것입니다. 또한 ViewStockNext 작업을 수행하지 않고 대신 인덱스가있는 ViewStock 작업을 고려해야합니다. (내 2 센트)


바꾸어 말하면 자렛 메이어의 답변을 , 당신은 'ID'로 매개 변수 이름을 변경하거나이 같은 경로를 추가해야합니다 :

routes.MapRoute(
        "ViewStockNext", // Route name
        "Inventory/ViewStockNext/{firstItem}",  // URL with parameters
        new { controller = "Inventory", action = "ViewStockNext" }  // Parameter defaults
    );

그 이유는 기본 경로가 매개 변수가 없거나 'id'라는 매개 변수가있는 작업 만 검색하기 때문입니다.

편집 : 헤, 결코 신경 쓰지 않는 Jarret은 게시 후 경로 예제를 추가했습니다.


Headspring은 액션의 속성에서 매개 변수에 별칭을 추가 할 수있는 멋진 라이브러리를 만들었습니다. 이것은 다음과 같습니다.

[ParameterAlias("firstItem", "id", Order = 3)]
public ActionResult ViewStockNext(int firstItem)
{
    // Do some stuff
}

이를 통해 다른 매개 변수 이름을 처리하기 위해 라우팅을 변경할 필요가 없습니다. 라이브러리는 또한 여러 번 적용을 지원하므로 여러 매개 변수 철자를 매핑 할 수 있습니다 (퍼블릭 인터페이스를 손상시키지 않고 리팩토링 할 때 편리함).

Nuget 에서 얻을 수 있으며 여기 에서 Jeffrey Palermo의 기사를 읽을 수 있습니다.


public ActionResult ViewNextItem(int? id)id정수를 nullable 형식으로 만들고 string <-> int 변환이 필요하지 않습니다.


또는 경로 속성으로 수행하십시오.

public class InventoryController : Controller
{
    [Route("whatever/{firstItem}")]
    public ActionResult ViewStockNext(int firstItem)
    {
        int yourNewVariable = firstItem;
        // ...
    }
}

ASP.NET Core 태그 도우미 기능 사용 :

<a asp-controller="Home" asp-action="SetLanguage" asp-route-yourparam1="@item.Value">@item.Text</a>

이를 수행하는 또 다른 방법이 있습니다 (Stephen Walther의 Pager 예제 에서 자세히 설명 됨).

기본적으로보기에 링크를 만듭니다.

Html.ActionLink("Next page", "Index", routeData)

In routeData you can specify name/value pairs (e.g., routeData["page"] = 5), and in the controller Index function corresponding parameters receive the value. That is,

public ViewResult Index(int? page)

will have page passed as 5. I have to admit, it's quite unusual that string ("page") automagically becomes a variable - but that's how MVC works in other languages as well...


The reason for the special treatment of "id" is that it is added to the default route mapping. To change this, go to Global.asax.cs, and you will find the following line:

routes.MapRoute ("Default", "{controller}/{action}/{id}", 
                 new { controller = "Home", action = "Index", id = "" });

Change it to:

routes.MapRoute ("Default", "{controller}/{action}", 
                 new { controller = "Home", action = "Index" });

Or, you could try changing the parameter type to string, then convert the string to an integer in the method. I am new to MVC, but I believe you need nullable objects in your parameter list, how else will the controller indicate that no such parameter was provided? So...

public ActionResult ViewNextItem(string id)...

참고URL : https://stackoverflow.com/questions/155864/asp-net-mvc-passing-parameters-to-the-controller

반응형