将属性从控制器传递给Model

时间:2011-06-06 19:29:08

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

我试图将一个变量从我的Controller中的方法传递给一个Model中的方法。由于模型中的方法采用一个参数(之前设计过),因此我无法将变量作为参数传递给模型中的方法。而且,此模型中的方法也被其他控制器调用,因此如果我更改参数,我也必须更改所有控制器,这将是一项单调乏味的任务。 到目前为止我一直在尝试的是 - 我创建了一个MyVariableClass并声明了一个属性。然后我实例化了该类并将属性字符串设置为我想要传递的变量。现在,在我的Model的方法中,我再次实例化了相同的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);
    }

和MyVariableClass

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

和我的模型中的方法

  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 ....
   }

有人解决这个问题吗?在此先感谢!

2 个答案:

答案 0 :(得分: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);
  }

答案 1 :(得分:0)

尝试使用session variable

相关问题