【问题标题】:asp.net how to retrieve data from database in my controller [closed]asp.net 如何从我的控制器中的数据库中检索数据[关闭]
【发布时间】:2020-05-27 15:15:57
【问题描述】:

我有一个这样的模型

class Student 
{
   public int Id {get; set;}
   public string Name {get;set;}
   public string College {get;set;}
}

我有一个这样的 Homecontroller 方法,

public ActionResult GetData()
        {
            Student data = new Student();
            return Json(data.Name);
        }

它返回的 json 数据为空。但是我的数据库中只有几行数据。当为我的 ajax 调用上述方法时,如何返回数据库中的所有“名称”?

【问题讨论】:

  • 你还没到应该问问题的地步。您应该做的第一件事(在提出问题之前)是研究问题并尝试一些事情。然后,如果您没有成功,请粘贴您拥有的代码、您的研究和理解、您的期望和正在发生的事情。
  • 您应该使用您的DbContext 连接到您的数据库。
  • @HamedMoghadasi 实际上我迷路了,不知道该搜索什么。感谢您为我指明正确的方向。

标签: c# asp.net model-view-controller


【解决方案1】:

型号

using System.ComponentModel.DataAnnotations.Schema;

[Table("StudentMaster")]  //write here table name
public class Student
{
   public int Id {get; set;}
   public string Name {get;set;}
   public string College {get;set;}
}

然后为您的数据库引用创建一个上下文类

控制器

//here you need to create a context class object

dbcontext _contextclass = new dbcontext(); 

public ActionResult GetData()
{      
    return View(db._contextclass .ToList());
}

【讨论】:

  • 感谢您的指导@Rahul。我收到上述代码的“无数据库提供程序”错误。但后来发现我需要通过使用“using()”模式或依赖注入模式来稍微修改上面的代码才能工作。非常感谢。
  • @Pal 如果您使用实体框架,则无需创建上下文类,请记住这一点,或者如果您使用代码优先方法,则创建一个上下文类。上下文类只不过是我们的应用程序和 SQL 之间的中介
猜你喜欢
  • 1970-01-01
  • 2016-02-07
  • 1970-01-01
  • 1970-01-01
  • 2015-04-26
  • 2013-07-14
  • 1970-01-01
  • 1970-01-01
  • 2021-03-03
相关资源
最近更新 更多