ASP.NET 核心:将存储过程的结果传递给下拉列表

ASP.NET CORE: Passing result of stored procedure to dropdown

我正在使用 ASP.NET Core 和 Razor 页面。我使用 ADO.NET 模型从存储过程中获取数据。我不确定如何将此结果数据传递给下拉列表。我正在根据 https://www.learnentityframeworkcore.com/raw-sql#database.executesqlcommand 中可用的教程进行尝试,最后一部分 - 通过 Context.Database 属性.

利用 ADO.NET

如何将包含 "Desc" 列的存储过程的结果传递给下拉列表。

下面是使用的代码

//index.cshtml
<select class="form-control" required multiple id="selLOB" asp-for="SelectedLOBs" asp-items="Model.LOBOptions"></select>

//index.cshtml.cs
public class IndexModel : PageModel
    {
        private readonly MyDbContext _dbContext;
        public IndexModel(MyDbContext dbContext)
        {
            _dbContext = dbContext;
        }
        public List<LOB> lOBs { get; set; } = new List<LOB>();

        [BindProperty]
        public string[] SelectedLOBs { get; set; }

        public SelectList LOBOptions { get; set; }

        public async Task OnGetAsync()
        {    
            using (var command = _dbContext.Database.GetDbConnection().CreateCommand())
            {
                command.CommandType = System.Data.CommandType.StoredProcedure;
                 await _dbContext.Database.ExecuteSqlCommandAsync("EXECUTE sp");
            }
        }
    }

// Model
 public class LOB
    {
         public string Desc { get; set; }       
    }

// Data
 public class MyDbContext : DbContext
    {
              public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
        {
        }
}

//startup.cs
  public void ConfigureServices(IServiceCollection services)
        {           
            services.AddMvc();
            ConnectionString = Configuration["TestConnectionString:DatabaseConnection"]; // Get Connection String from Appsetting.json
  services.AddDbContext<MyDbContext>(options =>
       options.UseSqlServer (ConnectionString));

        }

尝试了这个新代码:

using (var command = _dbContext.Database.GetDbConnection().CreateCommand())
            {
                command.CommandType = System.Data.CommandType.StoredProcedure;
                command.CommandText = "sp";
                _dbContext.Database.OpenConnection();
                 using (var result = command.ExecuteReader())
                {
                    if (result.Read())
                    {
                        LOBOptions = new SelectList(result, "Desc");
                    }
                }
            }

但出现 InvalidOperationException 错误:reader 关闭时调用 FieldCount 的尝试无效

尝试了以下代码:

public async Task OnGetAsync()
        {                 
            using (var command = _dbContext.Database.GetDbConnection().CreateCommand())
            {
                command.CommandType = System.Data.CommandType.StoredProcedure;
                command.CommandText = "sp";
                _dbContext.Database.OpenConnection();

                using (var result = command.ExecuteReader())
                {
                    LOB lob = new LOB();
                    lob.Desc = Convert.ToString(result["Desc"]);
                    lOBs.Add(lob);
                    LOBOptions = new SelectList(lOBs, "Desc", "Desc");

                }
            }

        }

并在

中出现错误
lob.Desc = Convert.ToString(result["Desc"]);

要填充视图中的下拉列表,需要将 SelectList 类型的对象从服务器传递到视图。这可以通过视图 ViewBag 或作为模型的一部分传递。

SelectList 的对象可以通过从数据库中填充数据来创建。这就是你想要做的。

您只是按照评论中建议的答案进行操作,同时您还需要在 MSDN 上阅读相关内容。您还需要阅读有关 ADO.NET 的内容。

尽管如此,以下是我建议使用数据库中的数据填充下拉列表的方法。

以下是我的存储过程的代码。

CREATE PROCEDURE GetProductCategories
AS
BEGIN
    SELECT CategoryId, CategoryName FROM ProductCategory
END
GO

以下是我的模型class。

public class ProductModel
{
    public int Id { get; set; }

    public string Name { get; set; }

    public int CategoryId { get; set; }

    public  SelectList Categories { get; set; }
}

以下是我如何从 C# 代码执行存储过程并在我的控制器中填充类别 selectList class。

var connectionString = "connectionString";
var productModel = new ProductModel();

List<SelectListItem> listItems = new List<SelectListItem>();

using (var connection = new SqlConnection(connectionString))
{
    using (var command = connection.CreateCommand())
    {
        command.CommandText = "GetProductCategories";
        command.CommandType = CommandType.StoredProcedure;
        connection.Open();

        var dataReader = command.ExecuteReader();

        while (dataReader.Read())
        {
            var item = new SelectListItem();
            item.Text = dataReader["CategoryName"].ToString();
            item.Value = dataReader["CategoryId"].ToString();
            listItems.Add(item);
        }
    }
}

productModel.Categories = new SelectList(listItems);