假设有控制器AController 和控制器BController,控制器A的命名空间为nameSpaceA,控制器B的命名空间为nameSpaceB
控制器B中有方法:
public JsonResult func(){
bool result = true
return Json(true, JsonRequestBehavior.AllowGet);
}
public static JsonResult func_1(){
bool result = true
return Json(new { result_1 = result,result_2 = "成功"}, JsonRequestBehavior.AllowGet);
}
当在控制器A中调用B中方法时:
public void funcA(){
//当方法为控制器的非静态成员时,实例化控制器,并调用方法
nameSpaceB.Controllers.B BController = new nameSpaceB.Controllers.B();
var jsonResult = BController.func();
//jsonResult.Data中只存在一个bool类型结果,直接转换jsonResult.Data为bool类型并执行后续逻辑
bool result = (bool)jsonResult.Data;
if (result){
//doSomething
}
//当方法为控制器的静态成员时,使用控制器名直接调用方法
var jsonResult = BController.func_1();
//先获取jsonResult.Data类型
Type resultType = jsonResult.Data.GetType();
//通过获取类型获取其中公共属性的值并强转为其本身的类型,result_1在返回结果中为bool类型,将其转换为bool类型使用,result_2在返回结果中为string类型,将其转换为string类型使用
bool result_1 = (bool)resultType.GetProperty("result_1").GetValue(jsonResult.Data);
string result_2 = (string)resultType.GetProperty("result_2").GetValue(jsonResult.Data);
//doSomething
}
本文介绍了在ASP.NET MVC中如何从一个控制器调用另一个控制器的方法,区分静态与非静态成员的调用方式。在调用静态方法时,演示了如何获取并转换返回JsonResult中的数据,包括提取不同类型的结果属性。
558

被折叠的 条评论
为什么被折叠?



