【发布时间】:2019-03-12 17:56:51
【问题描述】:
我正在使用 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 错误:阅读器关闭时调用 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"]);
【问题讨论】:
-
您需要将来自存储过程的数据加载到
LOBOptionsselectList。 -
嗨 Chetan。你能展示一下它的代码示例吗
-
嗨 Chethan。 await 行应该设置为 LOBOptions 吗?我无法设置列表