创建所有模型特性的多选列表

本文关键字:列表 模型 创建 | 更新日期: 2024-09-25 01:16:17

在我的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]等属性,但在我的视图中显示的只有标题为"容量"、"计数"answers"项目"的复选框?

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

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://stackoverflow.com/questions/5796151/export-model-data-to-excel-mvc
    //https://landokal.wordpress.com/2011/04/28/asp-net-mvc-export-to-excel-trick/

}

我要做的是获得所有INV_Assets属性的多选列表,然后使用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中提取所选项目。您也可以在post操作中添加一个List<string> propertyList参数,它应该会自动绑定。

编辑3:

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

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

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

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

上面的代码没有经过测试,但它应该给出了如何处理帖子的想法。