I have an sms sms application, which has different templates that users can use to send their SMSs, I used different view to represent different templates, however I want to use one action method to send an SMS, i might be different templates but at the end of the day user will send an sms which has two parameters, message itself and cell number to which this sms is to be send to,
Here is my 3 templates for now
[HttpGet]
public ActionResult BookingServiceReminder()
{
return View();
}
[HttpGet]
public ActionResult ServiceReminder()
{
return View();
}
[HttpGet]
public ActionResult DetailedReminder()
{
return View();
}
[HttpPost]
public ActionResult SendSMS(string message, string cellNumber)
{
if (_dbManager.SendSMS(cellNumber, message, User.Identity.Name))
{
TempData["Success"] = "Message was successfully sent";
}
else
{
TempData["Error"] = "An error occured while sending the message";
}
return RedirectToAction("BookingServiceReminder");
}
My question is, is there a way of using one method for all this views, I dont want to have multiple post methods which will almost have same code except the redirectToAction on which I want to return then current view(current template).
Yes, you can.
You would need to keep track someway that at which action user should be redirected after sending the sms.
One way for it is you can pass the flag back to view and post it as hidden field to determine that which action should be redirected to :
[HttpGet]
public ActionResult BookingServiceReminder()
{
ViewBag.RedirectTo = "BookingServiceReminder";
return View();
}
[HttpGet]
public ActionResult ServiceReminder()
{
ViewBag.RedirectTo = "ServiceReminder";
return View();
}
[HttpGet]
public ActionResult DetailedReminder()
{
ViewBag.RedirectTo = "DetailedReminder";
return View();
}
and in View you can have a hidden field which would post to action :
<input type="hidden" value="@ViewBag.RedirectTo" name="RedirectTo">
and in action add a new paramter:
[HttpPost]
public ActionResult SendSMS(string message, string cellNumber,string RedirectTo)
{
if (_dbManager.SendSMS(cellNumber, message, User.Identity.Name))
{
TempData["Success"] = "Message was successfully sent";
}
else
{
TempData["Error"] = "An error occured while sending the message";
}
return RedirectToAction(RedirectTo);
}