0

我有一个自动生成 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<ERPCustomerSupplier.Models.CurrencyList>'隐式转换为'System.Collections.Generic.IEnumerable<Microsoft.AspNetCore.Mvc.Rendering.SelectListItem>' . 存在显式转换(您是否缺少演员表?)”

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

4

2 回答 2

1

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

你应该使用 SelectListItem 来生成一个下拉列表,下面是一个演示(数据库是 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>

结果:

在此处输入图像描述

于 2021-04-15T03:56:58.470 回答
0

客户类从普通列表项修改为 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>

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

于 2021-04-19T05:44:05.873 回答