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

时间:2015-03-03 15:46:39

标签: c# asp.net-mvc razor asp.net-mvc-5 export-to-excel

在我的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]等属性,但在我的视图中呈现的唯一内容是标题为“容量”,“计数”和“项目”的复选框?

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

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; }
    }
}

1 个答案:

答案 0 :(得分:0)

试试这样:

@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参数,它应该自动绑定。

编辑3:

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

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

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

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

上面的代码没有经过测试,但应该知道如何处理帖子。