如何使用 entity framework 或 MVC 项目绑定 HTML select 元素?

How to bind HTML select element using either entity framework or MVC project?

我当前的项目是基于 MVC 的。我坚持尝试从我的 SQL 服务器数据库 table 填充 select 元素。控制器正在 DataTable 对象中接收数据库数据。此数据需要在页面加载时绑定到 HTML select 元素。

如有任何帮助,我们将不胜感激。

控制器代码 GET 方法操作

 // GET: SearchPopulate
 [HttpGet]
 public ActionResult SearchHome()
 {
        SearchPopulateMaster empPopulate = new SearchPopulateMaster();
        empPopulate.emp = PopulateEmps();
        return View();
 }

 private static List<SelectListItem> PopulateEmps() 
 {
        List<SelectListItem> items = new List<SelectListItem>();
        DataTable localdt = new DataTable();
        localdt = DALAcess.getDataFromSql("SELECT id,AgentName from [atmcolle_COMM_U88].[dbo].ATM_M_empMaster");
        return items;
 }

查看代码 .cshtml 文件

<form asp-controller="SearchHome" asp-action="SearchHome">
    <!--Non-hardcoded retrieved from database-->
    <select name="selEmp" id="selEmp">
        <option>Please select one</option>
    </select>

    <input type="submit" />
    <!--Non-hardcoded retrieved from database-->
</form>

您似乎正试图将您的 Data 绑定到 HTML dropdown (HTML Select Tag) 中,后者使用来自您数据库的 entity framework

您可以尝试以下步骤:

Model:

假设我有这样的模型:

public class Agent
    {
        [Key]
        public int Id { get; set; }
        public string AgentName { get; set; }
    }

Controller:

    public ActionResult BindHtmlSelectElement()
    {
        //Bind Dropdown
        List<Agent> agent = PopulateEmps();
        ViewBag.Agent = new SelectList(agent, "Id", "AgentName");
        return View();
    }

View:

   @model MVCApps.Models.Agent
    @{
        ViewData["Title"] = "BindHtmlSelectElement";
    }
    
    <h4><strong>BindHtmlSelectElement</strong> </h4>
    <hr />
    <div class="form-group">
        <label  class="control-label col-md-2">Agent</label>
        <div class="col-md-10">
            <select asp-items="ViewBag.Agent" value=""  class="form-control" asp-for="Id"></select>
        </div>
    </div>

Output:

Note: In your PopulateEmps method return your agent list. And be conscious about the convension as well I made the id as Id be carefull while replace that to get rid of any error.

Update: 您也可以尝试访问您的 Agent 查询,如下所示

public List<Agent> QueryBuilder()
        {
            using (var connection = new SqlConnection("Server=ServerName;Database=YouDatabaseName;Trusted_Connection=True;MultipleActiveResultSets=true"))
            {

                List<Agent> viewModeList = new List<Agent>();
                await connection.OpenAsync();
                var command = connection.CreateCommand();
                command.CommandText = "SELECT id,AgentName from [atmcolle_COMM_U88].[dbo].ATM_M_empMaster";
                SqlDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    Agent viewModel = new Agent();
                    viewModel.Id= reader["id"].ToString(); // Remember to convert property in correct format
                    viewModel.AgentName = reader["AgentName"].ToString();
                    viewModeList.Add(viewModel);

                }
                reader.Close();
                command.Dispose();
                connection.Close();
                return viewModeList;
            }

        }

Update The Controller Like Below:

public ActionResult BindHtmlSelectElement()
    {
        //Bind Dropdown
        List<Agent> agent = QueryBuilder();
        ViewBag.Agent = new SelectList(agent, "Id", "AgentName");
        return View();
    }

希望以上步骤能指导您实现目标。