来自使用Request [" name"]变量的其他控制器的call方法

时间:2016-02-02 09:06:37

标签: c# asp.net asp.net-mvc asp.net-mvc-3 request

我使用的是Asp.net MVC。我的HTML代码是:

<form action="/MobilesController/SaveMobilesAd">
      <input type="text" name="brand" />
      <input type="text" name="color" />
      <!-- other stuff -->
      <input type="submit" />
</form>

有超过10个属性,如brand,color,我必须在15个不同的页面上输入数据。为了避免代码冗余,我在这个函数中创建了一个函数MyAd()来实现我的所有逻辑,我只需要在任何需要的地方调用这个函数。

public class AdController: Controller
    {
         public void MyAd()
         {
              string brand = Request["brand"];
              string color = Request["color"];
              //other stuff. take data from Request variables and save in database.
         }
    }

现在在另一个控制器中使用MyAd()

public class MobilesController:Controller
{
     AdController ad = new AdContoller();
     public ActionResult SaveMobilesAd()
     {
           //some stuff.
           ad.MyAd();
     }
}

现在的问题是,当我在另一个控制器中调用MyAd()时,它会给出异常

  

对象引用未设置为对象的实例

<{1>} Request["brand"]。我怎样才能避免这种异常,或者有其他方法来实现这个目标?

1 个答案:

答案 0 :(得分:0)

当您调用AdController ad = new AdContoller(); Request对象时,或者更确切地说是实例时,不会共享。 Request中的MobilesController对象与AdController中的public void MyAd(HttpRequestBase externalRequest = null) { HttpRequestBase currentRequest = externalRequest ?? Request; string brand = currentRequest ["brand"]; string color = currentRequest ["color"]; //... } 对象不同。你能做的是以下几点:

Request

然后您可以通过传递另一个Controller实例的AdController来调用它(如果需要,即如果不是从public class MobilesController: Controller { AdController ad = new AdContoller(); public ActionResult SaveMobilesAd() { //some stuff. ad.MyAd(Request); } } 调用):

Dictionary<string, string>

话虽这么说,我对这种方法并不熟悉。它接触到我,你可以(应该?)重构这个并创建一个通用的静态方法,比如一个 [[UIApplication sharedApplication] openURL:[NSURL URLWithString: @"http://www.mydomain.app.com"]]; 甚至一个自定义类,并处理数据。