2012-09-09 2 views
1

내가 사랑하는 PARAMS하지만이 작동하지 않습니다에 대한 작업을 정의하려고 :다른 매개 변수의 경우 동작을 정의하는 방법은 무엇입니까? - asp.net의 mvc4

public class HomeController : Controller 
    { 
    public ActionResult Index() 
    { 
     return View(); 
    } 

    public ActionResult Index(string name) 
    { 
     return new JsonResult(); 
    } 

    public ActionResult Index(string lastname) 
    { 
     return new JsonResult(); 
    } 

    public ActionResult Index(string name, string lastname) 
    { 
     return new JsonResult(); 
    } 
    public ActionResult Index(string id) 
    { 
     return new JsonResult(); 
    } 
} 

하지만 난 얻을 오류 :

컨트롤러 유형 'HomeController'조치 '지수'의 현재 요청 .... 다음 액션 메소드 사이의 모호

편집 :

하는 것이 가능하지 최선을 제안하십시오 그것을하는 방법.

감사합니다,

Yosef는

답변

1

당신은 ActionNameAttribute 속성을 사용할 수 있습니다 그리고

[ActionName("ActionName")] 

을, 당신은 작업 방법의 각각 다른 이름이있을 것이다.

+0

덕분에, yopu 내가 쓰는 내 경우에 대한 몇 가지 예를 들어 줄 수 있습니까? – Yosef

1

같은 유형의 요청 (GET, POST 등)에 응답 할 때 오버로드 된 작업 메서드를 사용할 수 없습니다. 필요한 모든 매개 변수가있는 공용 메서드가 하나 있어야합니다. 요청에서 제공하지 않으면 null이되고 사용할 수있는 과부하를 결정할 수 있습니다.

이 단일 공용 메서드의 경우 모델을 정의하여 기본 모델 바인딩을 활용할 수 있습니다.

public class IndexModel 
{ 
    public string Id { get; set;} 
    public string Name { get; set;} 
    public string LastName { get; set;} 
} 

다음은 컨트롤러가 같아야 방법은 다음과 같습니다 컴파일러가 떨어져 그들에게 말할 수 없기 때문에

public class HomeController : Controller 
{ 
    public ActionResult Index(IndexModel model) 
    { 
     //do something here 
    } 
} 
1

이 두 가지가 함께 살 수 없다. 이름을 바꾸거나 삭제하거나 추가 매개 변수를 추가하십시오. 이것은 모든 클래스에 해당됩니다.

public ActionResult Index(string name) 
{ 
    return new JsonResult(); 
} 

public ActionResult Index(string lastname) 
{ 
    return new JsonResult(); 
} 

는 기본 매개 변수와 함께 하나의 방법을 사용해보십시오 :

public ActionResult Index(int? id, string name = null, string lastName = null) 
    { 
     if (id.HasValue) 
     { 
      return new JsonResult(); 
     } 

     if (name != null || lastName != null) 
     { 
      return new JsonResult(); 
     } 

     return View(); 
    } 

또는

public ActionResult Index(int id = 0, string name = null, string lastName = null) 
    { 
     if (id > 0) 
     { 
      return new JsonResult(); 
     } 

     if (name != null || lastName != null) 
     { 
      return new JsonResult(); 
     } 

     return View(); 
    } 
+0

모든 작업은 웹 서비스와 같은 http 만받습니다. – Yosef

관련 문제