라우팅 : 현재 작업 요청 […]이 다음 작업 방법간에 모호합니다.


100

Browse.chtml사용자가 검색어를 입력하거나 검색어를 비워 둘 수 있는보기가 있습니다. 검색어를 입력 할 때 페이지를로 연결 http://localhost:62019/Gallery/Browse/{Searchterm} 하고, 아무것도 입력하지 않은 경우 브라우저를로 연결하고 싶습니다 http://localhost:62019/Gallery/Browse/Start/Here.

이것을 시도하면 오류가 발생합니다.

컨트롤러 유형 'GalleryController'의 'Browse'작업에 대한 현재 요청은 다음 작업 메서드간에 모호합니다. System.Web.Mvc.ActionResult Browse (System.String) on ​​type AutoApp_MVC.Controllers.GalleryController System.Web.Mvc.ActionResult Browse (Int32, System.String) AutoApp_MVC.Controllers.GalleryController 형식

내가 MVC로하는 모든 일은 처음입니다. 이 시점에서 무엇을 시도해야할지 잘 모르겠습니다.

public ActionResult Browse(string id)
{
    var summaries = /* search using id as search term */
    return View(summaries);
}

public ActionResult Browse(string name1, string name2)
{
    var summaries = /* default list when nothing entered */
    return View(summaries);
}

Global.asax.cs에도 다음이 있습니다.

    routes.MapRoute(
         "StartBrowse",
         "Gallery/Browse/{s1}/{s2}",
         new
         {
             controller = "Gallery",
             action = "Browse",
             s1 = UrlParameter.Optional,
             s2 = UrlParameter.Optional
         });



    routes.MapRoute(
         "ActualBrowse",
         "Gallery/Browse/{searchterm}",
         new
         {
             controller = "Gallery",
             action = "Browse",
             searchterm=UrlParameter.Optional
         });

답변:


161

컨트롤러에서 이름이 같은 작업 메서드는 최대 2 개까지만 가질 수 있습니다. 이렇게하려면 1 개는이어야 [HttpPost]하고 다른 하나는이어야합니다 [HttpGet].

두 메서드 모두 GET이므로 작업 메서드 중 하나의 이름을 바꾸거나 다른 컨트롤러로 이동해야합니다.

2 개의 Browse 메서드가 유효한 C # 오버로드이지만 MVC 작업 메서드 선택기는 호출 할 메서드를 파악할 수 없습니다. 방법에 대한 경로를 일치 시키려고 시도 할 것이며 (또는 그 반대로)이 알고리즘은 강력한 유형이 아닙니다.

다른 작업 방법을 가리키는 사용자 지정 경로를 사용하여 원하는 작업을 수행 할 수 있습니다.

... Global.asax에서

routes.MapRoute( // this route must be declared first, before the one below it
     "StartBrowse",
     "Gallery/Browse/Start/Here",
     new
     {
         controller = "Gallery",
         action = "StartBrowse",
     });

routes.MapRoute(
     "ActualBrowse",
     "Gallery/Browse/{searchterm}",
     new
     {
         controller = "Gallery",
         action = "Browse",
         searchterm = UrlParameter.Optional
     });

... 컨트롤러에서 ...

public ActionResult Browse(string id)
{
    var summaries = /* search using id as search term */
    return View(summaries);
}

public ActionResult StartBrowse()
{
    var summaries = /* default list when nothing entered */
    return View(summaries);
}

구별하기 위해 속성을 적용 하여 컨트롤러에서 동일한 이름의 조치 메소드유지할 수도 있습니다 [ActionName]. 위와 동일한 Global.asax를 사용하면 컨트롤러는 다음과 같습니다.

public ActionResult Browse(string id)
{
    var summaries = /* search using id as search term */
    return View(summaries);
}

[ActionName("StartBrowse")]
public ActionResult Browse()
{
    var summaries = /* default list when nothing entered */
    return View(summaries);
}

위의 예에서 새보기를 만들어야합니까? ActionName 태그를 사용하는 것은 도움이되지 않는 것 같습니다. 모든 작업 메서드의 이름을 바꾸는 데만 작동한다고 생각하기 때문입니다 (동시에 둘 다 유지할 수 없음). MVC가 어떻게 작동하는지 아는 것이 좋습니다. 감사.
Dave

6
아니요, 새보기를 만들 필요가 없습니다. 두 작업에 대해 동일한보기를 계속 재사용 할 수 있습니다. 보기 이름을 첫 번째 인수로 전달하십시오return View("Browse", summaries);
danludwig

오버로딩이 향후 릴리스에 포함될 예정입니까? 경로 수정은 추가 작업이며 변경시 추가 유지 보수가 필요합니다.
Old Geezer

@OldGeezer는 아마 그렇지 않을 것입니다.
danludwig

4

질문이 언제이 솔루션을 사용할 수 있었는지 모르겠지만 다음을 사용할 수 있습니다.

Request.QueryString["key"]

따라서 이것은 문제에 대해 잘 작동합니다.

[HttpGet]
public ActionResult Browse()
{
    if( Request.QueryString["id"] != null )        
        var summaries = /* search using id as search term */
    else /*assuming you don't have any more option*/
        var summaries = /* default list when nothing entered */

    return View(summaries);
} 

2

기본 경로 앞에 RouteConfig.cs에 다음 코드를 추가 합니다.

routes.MapMvcAttributeRoutes();

다음과 같이 컨트롤러에 경로 속성을 추가합니다.

    [Route("Cars/deteals/{id:int}")]
    public ContentResult deteals(int id)
    {
        return Content("<b>Cars ID Is " + id + "</b>");
    }

    [Route("Cars/deteals/{name}")]
    public  ContentResult deteals(string name)
    {
        return Content("<b>Car name Is " + name + "</b>");

    }

1

요점은 요청 클래스를 사용하여 쿼리 문자열 매개 변수를 암시 적으로 테스트 할 필요가 없다는 것입니다.

MVC가 매핑을 수행합니다 (MVC 경로를 심각하게 변경하지 않은 경우).

따라서 액션 링크 경로

/umbraco/Surface/LoginSurface/Logout?DestinationUrl=/home/

정의 된 매개 변수를 사용하여 (표면) 컨트롤러에서 자동으로 사용할 수 있습니다.

public ActionResult Logout(string DestinationUrl)

MVC가 작업을 수행합니다.

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.