[英]Accessing variables from the aspx.cs class in my website! (ASP.NET Web Forms)
[英]Proper way to use a repository class in an webforms aspx.cs file ASP.NET Web forms
在ASP.NET Web窗体的aspx.cs文件中,在代码隐藏文件中实例化存储库类的实例的正确方法是什么。 我试过这样做就像你在MVC控制器中那样做,但似乎我错过了一些东西。 这是我到目前为止没有运气的尝试。
public partial class Ajax : System.Web.UI.Page
{
private Repository _repo;
public Ajax()
{
_repo = new Repository();
}
protected void Page_Load(object sender, EventArgs e)
{
}
[System.Web.Services.WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string CreateForm(object data)
{
_repo.Insert(data);
}
}
public class Repository()
{
public void Insert(object data)
{
//do something.
}
}
问题是当我尝试构建它时,visual studio给我以下错误:“非静态字段,方法或属性Ajax._repo需要一个对象引用”什么是给静态webmethod访问的正确方法Repository类的实例?
编辑:要澄清,在静态方法中使用存储库实例的最佳方法是什么?
Web方法必须是静态的。 他们无法访问实例成员。 您可以在静态方法中获取存储库。
[System.Web.Services.WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string CreateForm(object data)
{
Repository repo = new Repository();
repo.Insert(data);
}
或者更好的是,放弃WebMethod,而是开始在项目中使用Web API ,使用依赖注入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.