2009-07-05 1 views
2

컨트롤러 메소드가보기 좋게 호출되고 자바 스크립트를 통해 호출되면 JsonResult를 반환하는 뷰를 반환 할 수 있습니까? 나의 동기는 내 견해를 구현할 자유를 원하지만, 나는 두 개의 컨트롤러 메소드 (각각의 개별 시나리오에 대해 하나씩 ... 아래의 정교 참조)를 생성하지 않고도 이것을 수행하고 싶다.asp MVC : 제어기 메소드 호출 방법을 결정할 수 있습니까?

 
    
     public ActionResult Get(int id) 
     { 
      Person somePerson = _repository.GetPerson(id); 
      ViewData.Add("Person", somePerson); 
      return View("Get"); 
     } 
 

를하지만, 경우에하는의이 같은 컨트롤러 방법은 jQuery를 통해이라고 가정 해 봅시다 :의 내가 브라우저에서 www.example.com/person/get?id=232를 입력 생각한 경우

, 나는 Get(int id) 방법은 다음과 같은 일을 할 것

 
    
     //controller method called asynchronously via jQuery 
     function GetPerson(id){ 
      $.getJSON(
       "www.example.com/person/get", //url 
       { id: 232 }, //parameters 
       function(data) 
       { 
        alert(data.FirstName); 
       } //function to call OnComplete 
      ); 
     } 
 

나는 다음과 같이 행동 할 것이다 :

 
    
     public JsonResult Get(int id) 
     { 
      Person somePerson = _repository.GetPerson(id); 
      return Json(somePerson); 
     } 
 

답변

4

나는 그것을 알아 냈다. 위의 특정 시나리오에서, 나는 할 수있다 :

 
    
     if(Request.IsAjaxRequest()) 
     { 
      return Json(someObject); 
     } 
     else 
     { 
      ViewData.Add("SomeObject", someObject); 
      return View("Get"); 
     } 
 

....> _ <이

+0

당신이 다른 액션 메소드 –

+0

에서 동일한 기능을 사용할 수 있도록 내 대답에 IsAjax 속성을 사용하는 것이 좋습니다 내 ViewData 객체를 매개 변수로 취하는 전략 패턴에 부울 테스트를 캡슐화 할 계획입니다. 전략 클래스의 구현에서 Request.IsAjaxRequest()를 확인하고 View 또는 Json을 반환합니다. 나는 클래스의 재사용 성을 얻게 될 것이고, Json 접근법을위한 추가적인 방법을 쓰지 않아도된다. 저장소에서 검색하는 로직은 두 가지 방법으로 공유되며, 물론 복제하고 싶지는 않습니다. 나는 그걸 가지고 놀고 당신에게 알려줄거야. – Amir

4

당신은 ActionMethodSelector를 사용하여이 작업을 수행 할 수 있습니다 지금은이 문제에 더 "우아한"솔루션에 작업을 시작할 수 있습니다 속성.
먼저이처럼 속성을 만듭니다

public class IsAjaxRequest :ActionMethodSelectorAttribute 
    { 
     public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo) 
     { 
      return controllerContext.HttpContext.Request.IsAjaxRequest(); 
     } 

    } 

을 그 다음을 사용 :

public ActionResult Get(int id) 
{ 
      Person somePerson = _repository.GetPerson(id); 
      ViewData.Add("Person", somePerson); 
      return View("Get"); 
} 


[IsAjaxRequest] 
[ActionName("Get")] 
public ActionResult Get_Ajax(int id) 
{ 
     Person somePerson = _repository.GetPerson(id); 
     return Json(somePerson); 

} 
+0

Marwan에게 감사합니다. 고마워요. 아마 다음 행을 따라 뭔가를 할 것이다. return _viewStrategy.Resolve (Request, someObject); – Amir

관련 문제