代码之家  ›  专栏  ›  技术社区  ›  Amir

ASP MVC:是否可以确定如何调用控制器方法?

  •  2
  • Amir  · 技术社区  · 17 年前

    如果调用restfully,控制器方法是否可以返回视图,如果通过javascript调用,是否可以返回JSonResult。 我的动机是我想有自由地实现我的视图,但是我想这样做而不必创建两个控制器方法(每个单独的场景一个……见下面的详细介绍)。

    假设我输入 www.example.com/person/get?id=232 在浏览器中,我希望 Get(int id) 方法执行如下操作:

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

    但如果我们假设通过jquery调用相同的控制器方法:

        
            //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);
            }
        
    
    2 回复  |  直到 17 年前
        1
  •  4
  •   Amir    17 年前

    我知道了。在上面的特定场景中,我可以做到:

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

    我现在可以开始为这个问题制定一个更“优雅”的解决方案了。

        2
  •  4
  •   user434917    17 年前

    您可以使用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);
    
     }