Reputation: 148
I have a Controller which handles the Payment process, when I call it from the View like the below:
<input type="button" value="Create" onclick="location.href='@Url.Action("Pay", "Payment")'" />
It works fine, and it redirects me to PayPal Gateway .
But it doesn't work when I call the same method on a certain event from another controller like the below :
PaymentController payment = new PaymentController();
payment.PaymentWithPaypal(obj.Amount);
Here's a piece of code from the Payment Controller :
[System.Web.Http.HttpPost]
public ActionResult PaymentWithPaypal(string amount)
{
//getting the apiContext
APIContext apiContext = PaypalConfiguration.GetAPIContext();
try
{
string payerId = Request.Params["PayerID"];
if (string.IsNullOrEmpty(payerId))
{...}
}
}
I got this error :
{"Object reference not set to an instance of an object."} System.Exception {System.NullReferenceException}
it seems that the "Request" is null, and it has not HttpContext !
Okay what I need is to simulate the exact behavior of calling an ActionResult from a view .
Many Thanks,
Upvotes: 0
Views: 33
Reputation: 77294
Apart from the technical problems, what would you expect to happen? You cannot redirect to a different page in the middle of a controller call.
If you want to redirect to the action as the end of your controller call, use RedirectToAction
:
return RedirectToAction("PaymentController", "PaymentWithPaypal", new { PayerID = playerId, Amount = "$1.234" });
You could also call the controller method directly, if you made sure that you don't touch all the behind the scenes http logic. Why is PayerID
not a method parameter? If you make it a method parameter, it would be much easier to write automated tests, too.
Upvotes: 1