RedirectToAction
returns a response to the client telling it to make a new request to the specified action.
The
ViewBag
contents are not persisted between requests. Anything you add to the
ViewBag
before returning a redirection response will not be available when the browser makes the new request.
There are a couple of options here:
1) Don't use
RedirectToAction
:
public ActionResult SenddOTP()
{
...
ViewBag.otp = strrandom;
return SendEmailtoUser();
}
private JsonResult SendEmailtoUser()
{
string OTP = ViewBag.otp;
bool result = SendEmail("user@gmail.com", "Hello", OTP);
return Json(result, JsonRequestBehavior.AllowGet);
}
Or:
public ActionResult SenddOTP()
{
...
return SendEmailtoUser(strrandom);
}
private JsonResult SendEmailtoUser(string OTP)
{
bool result = SendEmail("user@gmail.com", "Hello", OTP);
return Json(result, JsonRequestBehavior.AllowGet);
}
The browser will make a single HTTP request, and there will be no redirection involved.
2) Use the
TempData
storage:
public ActionResult SenddOTP()
{
...
TempData["otp"] = strrandom;
return RedirectToAction(nameof(SendEmailtoUser));
}
public JsonResult SendEmailtoUser()
{
string OTP = TempData["otp"] as string;
bool result = SendEmail("user@gmail.com", "Hello", OTP);
return Json(result, JsonRequestBehavior.AllowGet);
}
This will still use two HTTP requests.
NB: In this case, you would need to validate that the
TempData
value existed, since the user could navigate directly to the
SendEmailToUser
action without going via the
SenddOTP
action.
NB2: There's only one "d" in "Send". :)