我使用的是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"]
。我怎样才能避免这种异常,或者有其他方法来实现这个目标?
答案 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"]];
甚至一个自定义类,并处理数据。