【问题标题】:call method from other controller that uses Request["name"] variable从使用 Request["name"] 变量的其他控制器调用方法
【发布时间】:2023-03-21 10:11:01
【问题描述】:

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

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

brand,color这样的属性有10多个,我必须在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() 时它会给出异常

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

Request["brand"] 上。我怎样才能避免这个异常或有任何其他方法可以实现这一点?

【问题讨论】:

  • 您是否尝试过为此使用Model
  • 你为什么使用 Request.就开个课吧。在 Action 参数中传递它的对象
  • 您不需要手动绑定值string brand = Request["brand"]。只需使用 brand 属性为该方法或模型定义 brand 参数,默认活页夹就可以完成这项工作。它在表单值、查询字符串、路由数据等中查找具有相同名称的变量
  • 你在 MVC 架构中创造了一个致命的罪恶。为此,您需要使用正确的 MVC OOP。使用模型,如果你想绑定对象参数以获得一点安全性。如果您想继续这样做,或者只是出于某种原因您确实需要这种方法。查看安德烈的答案。

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


【解决方案1】:

当您调用 AdController ad = new AdContoller(); 时,Request 对象,或者更确切地说是实例,不会被共享。 MobilesController 中的 Request 对象与 AdController 中的对象不同。您可以执行以下操作:

public void MyAd(HttpRequestBase externalRequest = null)
{
    HttpRequestBase currentRequest = externalRequest ?? Request;

    string brand = currentRequest ["brand"];
    string color = currentRequest ["color"];
    //...
}

然后您可以通过传递另一个 Controller 实例的 Request 来调用它(如果需要,即如果不是从 AdController 调用):

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

话虽如此,我对这种方法不太满意。在我看来,您可以(应该?)重构它并制作一个通用的静态方法,例如,Dictionary&lt;string, string&gt; 甚至是自定义类,并处理数据。

【讨论】:

  • 谢谢!我刚刚将Request 替换为System.Web.HttpContext.Current.Request
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-30
  • 1970-01-01
  • 1970-01-01
  • 2015-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多