【问题标题】:MVC Using parameter for pass data with Methods controllerMVC 使用参数通过方法控制器传递数据
【发布时间】:2014-10-30 13:25:19
【问题描述】:

如果可能的话,我想看看背后的代码,因为我需要将我通过Try Catch 获得的属性_errorId 传递给我的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");
        }
      }
}

我有一个Controller,其属性名为_errorId,我有一个获取此值并将其放入ViewBag,当我的try catch 返回相同的错误时,我将我的属性_errorId 放入其中我的Post Methods 和他们,当我得到错误号时,我用这个错误号设置了我的_errorId,我需要把这个号码放在我的ViewBag Index();

【问题讨论】:

  • 您可以将变量附加到 ViewBag 并稍后访问它 ViewBag.ErrorId = _errorId;或 _errorId = ViewBag.ErrorId;
  • 无论如何你都不需要重定向,你可以简单地返回视图......它将是相同的视图,如果你传递一个空模型,它不会显示预填充的值(尽管如果你是返回一个错误,最好显示输入的值,这样用户就不会丢失他们的工作)。

标签: c# asp.net-mvc asp.net-mvc-4 controllers viewbag


【解决方案1】:

不会更简单吗?

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);
  }
}

请记住,RedirectToAction 会花费一些处理时间。

【讨论】:

    猜你喜欢
    • 2011-07-07
    • 1970-01-01
    • 2019-01-27
    • 1970-01-01
    • 2015-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多