【问题标题】:Pass property from controller to Model将属性从控制器传递给模型
【发布时间】:2011-06-06 19:29:08
【问题描述】:

我试图将一个变量从我的控制器中的方法传递给模型中的方法。由于模型中的方法采用一个参数(之前设计的),我不能将我的变量作为参数传递给模型中的方法。而且,这个模型中的方法也被其他控制器调用,所以如果我改变参数,我也必须改变所有的控制器,这将是一个乏味的任务。 到目前为止我一直在尝试的是 - 我创建了一个 MyVariableClass 并声明了一个属性。然后我实例化了那个类并将属性字符串设置为我想要传递的变量。现在,在我的模型方法中,我再次实例化了相同的 MyVariableClass,但是当我这样做时,变量的值被设置为 null。我现在的代码是 -

 public ActionResult ItemInformation( string id)
     {
        //Pass a string to MyVariable
        MyVariableVClass params = new MyVariableClass();
        params.myVariable = "abc";

   //This is what My Model is taking as an argument(id), and I don't want to 
   //pass mYvariable along with that argument because it will break other controllers
  // too which calls this method
    var itemInformation = _repository.GetItemInformation(id);
   return View(itemInformation);
    }

和我的变量类

  public  class MyVariableClass
  {
     public string myVariable { get; set; }
  }

和My Model中的方法

  public IList<Items> GetItemInformation(string itemId)
    {

      MyVariableClass webType = new MyVariableClass();
      var _params = webType.myVariable;
       //Check this variable and perform database query 
      if (_params =="this") 
       {
        var query = myFirstQuery;
       }
      else
       {
       var query = mySecondQuery;
       }
     //return ....
   }

有人有解决办法吗?提前致谢!

【问题讨论】:

  • 您似乎没有将MyVariableClass(即params)的实例传递给任何东西。相反,您创建它两次,一次在您的控制器中,一次在您的模型中。那应该如何完成任何事情? (另外,你的模型真的不应该有行为——方法——它们旨在保存数据,而不是随机代码位的存储库。将 GetItemInformation 行为放在其他地方。它与模型无关。 )
  • 是的!实际上我的问题是如何在不更改 GetItemInformation 的当前参数的情况下将 MyVariableClass 的实例传递给 getItemInformation?

标签: asp.net asp.net-mvc-3 model controller parameter-passing


【解决方案1】:

为什么继承你的模型并覆盖GetItemInformation 方法不起作用?或者,更简单的是,为什么不用一个需要两个字符串的方法来重载GetItemInformation 方法呢?您的其他控制器仍然可以使用只接受单个字符串的控制器。

  public IList<Items> GetItemInformation(string itemId, MyVariableClass webType)
    {

      var _params = webType.myVariable;
       //Check this variable and perform database query 
      if (_params == "this") 
       {
        var query = myFirstQuery;
       }
      else
       {
       var query = mySecondQuery;
       }
     //return ....
   }

  public IList<Items> GetItemInformation(string itemId)
  {
     MyVariableClass fauxType = new MyVariableClass();
     fauxType.myVariable = "not this";

     return GetItemInformation(itemId, fauxType);
  }

【讨论】:

  • 我不使用重载的唯一原因是避免在两个方法上重复代码。我只需要变量值,以便我可以检查条件并编写我的 LINQ。所以,如果我重载GetItemInformation,对于一行代码,我必须重复我的整个方法。
  • @ACS 请查看我添加的代码。你真的不需要重复整个方法。
【解决方案2】:

尝试使用session variable

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-03
    • 1970-01-01
    • 2011-07-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多