Reputation: 154
I have a Controller Action which returns JsonResult as follows:
[HttpPost]
public ActionResult GetTotal(int AccountId)
{
Account account=context.Accounts.FirstOrDefault(s=>s.Id=AccountId);
theTotal=account.Sum(s=>.Amount);
return Json(theTotal);
}
The above action returns the Total to a Ajax function. However, in few instances I want to get the total in another controller action for further calculation before calling the return View in the action.
How Do i Get the json result in another controller action from the above Action? Thanks in advance.
Upvotes: 1
Views: 902
Reputation: 25360
Create a common service to reuse the logic:
public class MyAccountService{
private AppDbContext _context;
public MyAccountService(AppDbContext context){
this._context = context;
}
public int GetTotal(int AccountId){
Account account=this._context.Accounts.FirstOrDefault(s=>s.Id=AccountId);
return account.Sum(s=>s.Amount);
}
}
register it as a scoped service.
services.AddDbContext<AppDbContext>(options =>options.UseSqlServer(Configuration.GetConnectionString("AppDbContext")))
services.AddScoped<MyAccountService>();
And inject this service in your controllers as you need:
public class A1Controler :{
private AccountService _accountService
public A1Controller(MyAccountService accountService){
this._accountService=accountService;
}
[HttpPost]
public ActionResult GetTotal(int AccountId)
{
var theTotal=this._accountService.GetTotal(AccountId);
return Json(theTotal);
}
}
If you have another A2Controller
, simply do the same injection.
Upvotes: 1