0

I want to see the code behind if it's possible, because I need to pass the property _errorId that I get with my Try Catch to my View Index.

    public class PrincipalController : Controller
    {
      **private int _errorId;**        

      public ActionResult Index()
      {            
        ViewBag.HomeViewModel =  **_errorId** ;

        return View();
      }

      [HttpPost]
      public ActionResult Index(Cadastro cadastro)
      {
        try
        {
            //something
            cadastro.save();
            return RedirectToAction("Index");                
        }
        catch (Exception ex)
        {
            **_errorId = 1;**
            return RedirectToAction("Index");
        }
      }
}

I have a Controller with property named _errorId, and I have a to get this value and put it into a ViewBag, when my try catch returns same error, I put my property _errorId inside my Post Methods and them, when I get the error number I set my _errorId with this error's number, and them I need put this number in my ViewBag in Index();

İsmet Alkan
  • 5,361
  • 3
  • 41
  • 64
soamazing
  • 1,656
  • 9
  • 25
  • 32
  • 1
    You can attach variables to ViewBag and later access it ViewBag.ErrorId = _errorId; Or _errorId = ViewBag.ErrorId; – SBirthare Oct 30 '14 at 13:30
  • possible duplicate of [How to redirect to an action with parameters from other action without passing parameters?](http://stackoverflow.com/questions/5101919/how-to-redirect-to-an-action-with-parameters-from-other-action-without-passing-p) – avidenic Oct 30 '14 at 13:32
  • 1
    You don't need to redirect anyway, you can simply return the View... it will be the same View and if you pass an empty model it will not show prefilled values (although if you are returning an error it would be nice to show the values entered so users don't lose their work). – Tallmaris Oct 30 '14 at 13:47

1 Answers1

0

Did it will not be more simple?

public class PrincipalController : Controller
{
  public ActionResult Index()
  {
    return View();
  }

  [HttpPost]
  public ActionResult Index(Cadastro cadastro)
  {
    try
    {
        //something
        cadastro.save();
    }
    catch
    {
        ViewBag.ErrorId = 1;
    }
    return View(cadastro);
  }
}

Remember, RedirectToAction cost a few amount of processing time.

Thiago Lunardi
  • 749
  • 1
  • 5
  • 19