创建所有模型属性的 Multi-Select 列表?

Create Multi-Select list of all Model Properties?

在我的 MVC5 Code-First 应用程序中,我正在使用 EPPlus 处理一些导出到 Excel 的功能。我正在使用的视图是我的 ExportController - Index.cshtml 视图。我试图循环的模型是我的主要模型,INV_Assets

我在几个类似的问题中看到了下面的帖子(复选框只是为了测试)

@foreach (var property in Model.GetType().GetProperties())
{
    @Html.Label(property.Name)
    @Html.CheckBox(property.Name)
}

但它没有呈现我的模型属性?例如,我有 [owner][note][description] 等属性,但在我的视图上呈现的唯一内容是标题为 "Capacity"、"Count" 和"Item"?

以下是我的控制器操作和视图:

ExportController - 索引:

@using GridMvc.Html
@using System.Collections.Generic
@model  List<InventoryTracker.Models.INV_Assets>

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Export</h2>

@*@foreach (var prop in Model.GetType().GetProperties())
{
    @(Html.TextBox(prop.Name, prop.GetValue(Model, null)))
}*@

@*@foreach(var property in ViewData.ModelMetadata.Properties)
{
    <label>@(property.DisplayName??property.PropertyName)</label>
    @Html.Editor(property.PropertyName)
}*@

@foreach (var property in Model.GetType().GetProperties())
{
    @Html.Label(property.Name)
    @Html.CheckBox(property.Name)
}


<a href="/Export/Export" class="btn btn-default btn-sm noDecoration"><span class="glyphicon glyphicon-export"> Export</span></a>
<br />
<br />
<a href="/Export/ExportUsingEPPlus" class="btn btn-default btn-sm noDecoration"><span class="glyphicon glyphicon-export"> Export - EPPlus</span></a>

ExportController:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using InventoryTracker.DAL;
using OfficeOpenXml;


namespace InventoryTracker.Controllers
{
    public class ExportController : Controller
    {
        InventoryTrackerContext _db = new InventoryTrackerContext();

        // GET: Export
        public ActionResult Index()
        {
            var assetList = _db.INV_Assets.ToList();
            return View(assetList);
        }

        public ActionResult Export()
        {
            GridView gv = new GridView();
            gv.DataSource = _db.INV_Assets.ToList();
            gv.DataBind();
            Response.ClearContent();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment; filename=InventoryAssets-" + DateTime.Now + ".xls");
            Response.ContentType = "application/ms-excel";
            Response.Charset = "";
            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            gv.RenderControl(htw);
            Response.Output.Write(sw.ToString());
            Response.Flush();
            Response.End();

            return RedirectToAction("StudentDetails");
        }

        public ActionResult ExportUsingEPPlus()
        {

            //FileInfo newExcelFile = new FileInfo(output);
            ExcelPackage package = new ExcelPackage();
            var ws = package.Workbook.Worksheets.Add("TestExport");
            ws.Cells["A1"].Value = "Sample Export 1";


            var memoryStream = new MemoryStream();
            package.SaveAs(memoryStream);

            string fileName = "Exported-InventoryAssets-" + DateTime.Now + ".xlsx";
            string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

            memoryStream.Position = 0;
            return File(memoryStream, contentType, fileName);

        }

    }

    //
    //https://landokal.wordpress.com/2011/04/28/asp-net-mvc-export-to-excel-trick/


}

我试图做的是获取我所有 INV_Assets 属性的 multi-select 列表,然后使用 EPPlus 仅导出那些属性到 Excel。


编辑:

模型代码 INV_Assets:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using GridMvc.DataAnnotations;
using System.Web.Mvc;
using InventoryTracker.Models;

namespace InventoryTracker.Models
{
    [GridTable(PagingEnabled = true, PageSize = 30)]
    public class INV_Assets 
    {
        // Setting GridColumn Annotations allows you to use AutoGenerateColumns on view to auto create the Grid based on the model.


        public int Id { get; set; }

        public int Model_Id { get; set; }
        [ForeignKey("Model_Id")]
        public virtual INV_Models Model { get; set; }

        [Required]
        public int Manufacturer_Id { get; set; }
        [ForeignKey("Manufacturer_Id")]
        public virtual INV_Manufacturers Manufacturer { get; set; }

        [Required]
        public int Type_Id { get; set; }
        [ForeignKey("Type_Id")]
        public virtual INV_Types Type { get; set; }

        [Required]
        public int Location_Id { get; set; }
        [ForeignKey("Location_Id")]
        public virtual INV_Locations Location { get; set; }

        public int Vendor_Id { get; set; }
        [ForeignKey("Vendor_Id")]
        public virtual INV_Vendors Vendor { get; set; }

        [Required]
        public int Status_Id { get; set; }
        [ForeignKey("Status_Id")]
        public virtual INV_Statuses Status { get; set; }

        public string ip_address { get; set; }

        public string mac_address { get; set; }

        [DataType(DataType.MultilineText)]
        public string note { get; set; }
        public string owner { get; set; }

        //[DataType(DataType.Currency)]
        //[DisplayFormat(DataFormatString="{0:C}", ApplyFormatInEditMode=true)]
        [DisplayFormat(DataFormatString = "{0:#,###0.00}", ApplyFormatInEditMode=true)]
        public decimal cost { get; set; }
        public string po_number { get; set; }

        [DataType(DataType.MultilineText)]
        public string description { get; set; }

        public int invoice_number{ get; set; }

        [Required]
        public string serial_number { get; set; }

        [Required]
        public string asset_tag_number { get; set; }

        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
        public DateTime? acquired_date { get; set; }

        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
        public DateTime? disposed_date { get; set; }

        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
        public DateTime? verified_date { get; set; }

        [Required]
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
        public DateTime created_date { get; set; }

        [Required]
        public string created_by { get; set; }

        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}")]
        public DateTime? modified_date { get; set; }

        public string modified_by { get; set; }

        // Flag to specify if item is available? (Not signed out, not auctioned, recycled, etc.)
        //public bool available { get; set; }
    }
}

这样试试:

@Html.ListBox("PropertyList", typeof(INV_Assets).GetProperties().Select(p => new SelectListItem { Text = p.Name, Value = p.Name, Selected = false })

编辑:

更改了调用 GetProperties() 的对象的类型。在你的 Model 上调用它之前,它是一个列表。但是您真正想要做的是在存储在列表中的对象类型上调用它。

编辑 2:

更改为 ListBox 而不是 ListBoxFor。由于您没有使用视图模型,因此您需要从 POST 上的 Request 中提取所选项目。您还可以将 List<string> propertyList 参数添加到 post 操作,它应该会自动绑定。

编辑 3:

要在 post 操作中获取数据,您必须将列表框包装在一个表单中,如下所示:

@using (Html.BeginForm("ExportProps", "Export") {
    @Html.ListBox(...)
}

下面是如何在 POST 操作中获取提交的数据:

[HttpPost]
public ActionResult ExportProps(List<string> propertyList) {
    // do stuff with your data here
}

以上代码未经过测试,但应该可以了解如何处理 post。