【问题标题】:ASP.NET Core Assign database values to a dropdown list for Edit actionASP.NET Core 将数据库值分配给编辑操作的下拉列表
【发布时间】:2021-04-14 15:53:08
【问题描述】:

我有一个自动生成 CRUD 的控制器,我正在尝试将从数据库中获取的值填充到下拉列表中。 我的模型类如下所示

using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace ERPCustomerSupplier.Models
{
    public class Customer
    {
        [Display(Name = "ID")]
        public int ID { get; set; }
        [Display(Name = "User")]
        public string REQ_USERNAME { get; set; }

        [Display(Name = "Date")]
        public string REQ_DATE { get; set; }

        [Display(Name = "Status")]
        public string STATUS { get; set; }
        [Display(Name = "Customer Type")]
        public string CUSTOMER_TYPE { get; set; }
        [Display(Name = "Number")]
        public string CUSTOMER_NUMBER { get; set; }
        [Display(Name = "Name")]
        public string ORGANIZATION_NAME { get; set; }
        [Display(Name = "Country")]
        public string COUNTRY { get; set; }
        [Display(Name = "Address")]
        public string ADDRESS_LINE { get; set; }
        [Display(Name = "City")]
        public string CITY { get; set; }
        [Display(Name = "State")]
        public string STATE { get; set; }
        [Display(Name = "Operating Unit")]
        public string OPERATING_UNIT { get; set; }
        [Display(Name = "Currency")]
        public string CURRENCY { get; set; }
        [Display(Name = "Credit Limit")]
        public string CREDIT_LIMIT { get; set; }
        [Display(Name = "Credit Terms")]
        public string CREDIT_TERMS { get; set; }
        [Display(Name = "Bill To")]
        public string BILL_TO { get; set; }
        [Display(Name = "Ship To")]
        public string SHIP_TO { get; set; }
        [Display(Name = "Contact Person")]
        public string CT_PERSON { get; set; }
        [Display(Name = "Job Title")]
        public string CT_JOB_TITLE { get; set; }
        [Display(Name = "Department")]
        public string CT_DEPARTMENT { get; set; }
        [Display(Name = "Mobile")]
        public string CT_MOBILE { get; set; }
        [Display(Name = "Email")]
        public string CT_EMAIL { get; set; }
        [Display(Name = "Phone")]
        public string CT_PHONE_NUMBER { get; set; }
        [Display(Name = "Ext")]
        public string CT_PHONE_EXT { get; set; }
        [Display(Name = "Fax")]
        public string CT_FAX_NUMBER { get; set; }
        [Display(Name = "Ext")]
        public string CT_FAX_EXT { get; set; }
        [Display(Name = "Assigned To")]
        public string ASSIGNEE_USERNAME { get; set; }
        [Display(Name = "Viewed Status")]
        public string VIEWED { get; set; }
        [Display(Name = "Territory")]
        public string TERRITORY_CODE { get; set; }
        [Display(Name = "Profile Class")]
        public string PROFILE_CLASS_ID { get; set; }
        [Display(Name = "Payment Terms")]
        public string PAYMENT_TERMS_NAME { get; set; }
        [Display(Name = "Payment Terms ID")]
        public string PAYMENT_TERMS_ID { get; set; }
        [Display(Name = "Profile Class")]
        public string PROFILE_CLASS_NAME { get; set; }
        [Display(Name = "Account Type")]
        public string ACCOUNT_TYPE { get; set; }


         public List<CurrencyList> currencyList { get; set; }

    }

    public class CurrencyList
    {
        public string CurrencyCode { get; set; }
        public string CurrencyName { get; set; }
    }
}

动作方法如下

public ActionResult Edit(int id)
        {
            CustomerDataAccessLayer customer = new CustomerDataAccessLayer();
            Customer customer1 = new Customer {
                currencyList = customer.GetAllCurrencies()
            };
 
            ModelState.Clear();
  
            return View(customer.GetAllCustomers().Find(Customer => Customer.ID == id));
         }

        // POST: CustomerController/Edit/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(int id, IFormCollection collection)
        {
            try
            {
                return RedirectToAction(nameof(Index));
            }
            catch
            {
                return View();
            }
        }

我使用数据访问层填充列表

  public List<CurrencyList> GetAllCurrencies()
        {
            //throw new NotImplementedException();
            List<CurrencyList> CurrenciesList = new List<CurrencyList>();

            string Orasql = @"Select CURRENCY_CODE, DESCRIPTION CURRENCY_NAME, PRECISION DECIMAL_POINTS  
                                from FND_CURRENCIES_VL where enabled_flag = 'Y'
                                ORDER BY 1";
            OracleConnection conn = new OracleConnection(connectionString);

            OracleCommand cmd = new OracleCommand(Orasql, conn);

            //OracleDataReader dr = new OracleDataReader();
            cmd.CommandType = CommandType.Text;

            OracleDataAdapter da = new OracleDataAdapter(cmd);
            DataTable dt = new DataTable();

            conn.Open();
            da.Fill(dt);
            conn.Close();
            foreach (DataRow dr in dt.Rows)
            {
                CurrenciesList.Add(
                    new CurrencyList
                    {
                        CurrencyCode=Convert.ToString(dr["CURRENCY_CODE"]),
                        CurrencyName=Convert.ToString(dr["CURRENCY_NAME"])
                    }
                    );
            }
               
            return CurrenciesList;

        }

最后的视图如下:

@model ERPCustomerSupplier.Models.Customer


@{
    ViewData["Title"] = "Edit";
    Layout = "~/Views/Shared/_SiteMaster.cshtml";
}

<h1>Edit</h1>

<h4>Customer</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Edit">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <table>
                <tr>
                    <td>
                        <label asp-for="CURRENCY" class="control-label"></label>
                    </td>
                    <td>
                       <select asp-for="CURRENCY" class="form-control form-control-sm" asp-items="Model.currencyList" />
                       <span asp-validation-for="CURRENCY" class="text-danger"></span>
                    </td>

我收到错误错误“CS0266:无法将类型'System.Collections.Generic.List'隐式转换为'System.Collections.Generic.IEnumerable'。存在显式转换(您是否缺少演员表?)"

这是我第一次尝试使用 .Net Core,欢迎提供所有帮助。

【问题讨论】:

    标签: asp.net-core


    【解决方案1】:

    错误信息意味着你必须使用List SelectListItem而不是List CurrencyList,

    你应该使用SelectListItem来生成一个下拉列表,下面是一个demo(数据库是sqlserver,你可以改成你的):

    public class Customer
    {
        [Display(Name = "ID")]
        public int ID { get; set; }
    
        [Display(Name = "Currency")]
        public string CURRENCY { get; set; }
        //....
        [NotMapped]   //add this
        public List<SelectListItem> currencyList { get; set; }  //change to SelectListItem
    }
    

    而我选择ViewBag来传递selectListitem,如果你也想传递会更容易

    获取客户模型中的其他属性:

    public IActionResult Index()
        {
            //Fill data from database to currentList, and use ViewBag to pass.
            ViewBag.currencyList = _context.CurrencyLists.Select(c => new SelectListItem { Value = c.CurrencyCode, Text = c.CurrencyName }).ToList();            
            return View();
        }
    

    查看,也改变表单,你的表单不会显示结果:

    <select asp-for="CURRENCY" class="form-control form-control-sm" asp-items="@(List<SelectListItem>)ViewBag.currencyList" >
         <option>-Please select-</option>
    </select>
    

    结果:

    【讨论】:

    • 能否分享一下从数据库中填充数据的代码?
    • @RajeshThampi 在demo中,ViewBag.currencyList = _context.CurrencyLists.Select(c =&gt; new SelectListItem { Value = c.CurrencyCode, Text = c.CurrencyName }).ToList();从数据库中获取数据(数据在CurrencyList表中,但是你需要使用你的oracle方式获取)并放入Viewbag,然后调用视图中的视图包。
    • 正如我所提到的,这是我第一次尝试使用 .Net Core(也没有太多接触 MVC)。我正在尝试从 EDIT 操作中填充此下拉列表。我可以看到的所有示例列表都是从索引操作填充的。从创建和编辑等其他操作中填充如何?我的要求将要求后续下拉列表引用以前的下拉值。
    • 你的意思是 Cascade 下拉列表吗?检查这个link
    • 我之前看过那个例子,因为我无法实现实体实体框架,所以不愿意尝试。我将使用 Oracle EBS 种子表,这些表没有主键或定义明确的关系。无论如何都会检查这个样本。谢谢蒂莎。
    【解决方案2】:

    客户类从普通列表项修改为 SelectListItem 列表

    public List<SelectListItem> CurrencyList { get; set; }
    

    使用 List 对象修改的列表种群

     public List<SelectListItem> GetAllCurrencies()
            {
                //throw new NotImplementedException();
                List<SelectListItem> CurrencyList = new List<SelectListItem>();
                string Orasql = @"Select CURRENCY_CODE, DESCRIPTION CURRENCY_NAME, PRECISION DECIMAL_POINTS  
                                    from FND_CURRENCIES_VL where enabled_flag = 'Y'
                                    ORDER BY 1";
                OracleConnection conn = new OracleConnection(connectionString);
                OracleCommand cmd = new OracleCommand(Orasql, conn);
                cmd.CommandType = CommandType.Text;
                OracleDataAdapter da = new OracleDataAdapter(cmd);
                DataTable dt = new DataTable();
    
                conn.Open();
                da.Fill(dt);
                conn.Close();
                foreach (DataRow dr in dt.Rows)
                {
                    CurrencyList.Add(new SelectListItem
                    {
                        Text = dr["CURRENCY_NAME"].ToString(),
                        Value = dr["CURRENCY_CODE"].ToString()
                    });
                }
                return CurrencyList;
            }
    

    修改编辑动作如下:

     public ActionResult Edit(int id)
            {
    
                CustomerDataAccessLayer customerdataaccesslayer = new CustomerDataAccessLayer();
                Customer customer1 = customerdataaccesslayer.GetCustomerData(id);
                customer1.CurrencyList = customerDataAccessLayer.GetAllCurrencies();
                ModelState.Clear();
                //return View(customerdataaccesslayer.GetAllCustomers().Find(Customer => Customer.ID == id)); 
                return View(customer1); 
             }
    

    修改Edit.cshtml如下:

    <td>
    <label asp-for="CURRENCY" class="control-label"></label>
    </td>
    <td>
    <select asp-for="CURRENCY" class="form-control form-control-sm" asp-items="Model.CurrencyList"></select>
    <span asp-validation-for="CURRENCY" class="text-danger"></span>
    

    希望这对其他人有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多