Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9073487
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T18:25:42+00:00 2026-06-16T18:25:42+00:00

I have the following view inside my asp.net mvc web application:, it simply display

  • 0

I have the following view inside my asp.net mvc web application:, it simply display the model data inside a table and there are three check boxes at the table Colum heads to select which columns should be extracted to excel (.xls) or text (.csv) files.
The view is:-

@model MvcApplication4.Models.SelectedCustomers

@{
    ViewBag.Title = "CustomerDetials";
}
<h3>Select Customers Detials</h3>
<table>
    <tr>
        <th>
            NAME @Html.CheckBox("Name",true)
        </th>
        <th>
            Description @Html.CheckBox("Description",true)
        </th>
        <th>
            Address @Html.CheckBox("Address",true)
        </th>
    </tr>
@foreach (var item in Model.Info) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.description)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.address)
        </td>
    </tr>
}

</table>
<p>
@Html.ActionLink("Back","customer","Home") |
<a href="">extract to excel</a> |
<a href="">extract to text file</a>
</p>

But can anyone provide some help on how i can accomplish the following:-

  1. Develop a action methods that will return & open an excel sheet containing the SelectedCustomer model objects when the user click on the ” extract to excel ” link.

  2. Develop a action methods that will return & open a .csv file containing the SelectedCustomer model objects when the user click on the ” extract to text file ” link.

  3. How can i only extract the columns that have their check box “selected”.

Thanks & Best Regards

:::UPDATED:::

I have updated my view to the following:-

@model MvcApplication4.Models.SelectedCustomers

@{
    ViewBag.Title = "CustomerDetials";
}

<h3>Select Customers Detials</h3>

@using (Html.BeginForm("Export", null))
{

<table>
        <tr>
            <th>
                NAME @Html.CheckBox("IncludeName",true)
            </th>
            <th>
                Description @Html.CheckBox("IncludeDescription",true)
            </th>
            <th>
                Address @Html.CheckBox("IncludeAddress",true)
            </th>
        </tr>

@foreach (var item in Model.Info) {
    <tr>

       <td>
                @Html.DisplayFor(modelItem => item.Name)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.description)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.address)
            </td>
    </tr>
}

</table>
<p>
@Html.ActionLink("Back","customer","Home") |
        <button type="submit" name="format" value="xls">extract to excel</button> |
        <button type="submit" name="format" value="csv">extract to text file</button>
    </p>}

Then have added the folloiwng action metthods:-

[HttpPost]
        public ActionResult Export(ExportViewModel exportOptions,IEnumerable<Account> sc)
        {
          //  var accounts = GetAccounts();
            if (exportOptions.Format == "csv")
            {
                return sc.AsCsvResult(exportOptions);
            }
            else if (exportOptions.Format == "xls")
            {
                return sc.AsXlsResult(exportOptions);
            }

            throw new NotSupportedException(
                string.Format("Unsupported format: {0}", exportOptions.Format)
            );
        }

And the following Model class:-

public abstract class ExportAccountsResult : ActionResult
{
    protected ExportAccountsResult(IEnumerable<Account> accounts, ExportViewModel exportOptions)
    {

        this.Accounts = accounts;
        this.ExportOptions = exportOptions;
    }

    protected IEnumerable<Account> Accounts { get; private set; }
    protected ExportViewModel ExportOptions { get; private set; }

    protected abstract string ContentType { get; }
    protected abstract string Filename { get; }

    public override void ExecuteResult(ControllerContext context)
    {
        var response = context.HttpContext.Response;
        response.ContentType = ContentType;
        var cd = new ContentDisposition
        {
            FileName = this.Filename,
            Inline = false
        };
        response.AddHeader("Content-Disposition", cd.ToString());

        // TODO: Use a real CSV parser here such as https://github.com/JoshClose/CsvHelper/wiki/Basics
        // and never roll your own parser as shown in this oversimplified
        // example. Here's why: http://secretgeek.net/csv_trouble.asp
        using (var writer = new StreamWriter(response.OutputStream))
        {
            foreach (var account in this.Accounts)
            {
               var values = new List<object>();
            if (this.ExportOptions.IncludeName)
            {
                values.Add(account.Name);
            }
            if (this.ExportOptions.IncludeDescription)
            {
                values.Add(account.Description);
            }
            if (this.ExportOptions.IncludeAddress)
            {
                values.Add(account.Address);
            }
            writer.WriteLine(string.Join(", ", values));
            }
        }
    }
}
}

and the following model class:-

namespace MvcApplication4.Models
{
    public class ExportViewModel
    {
        public string Format { get; set; }
        public bool IncludeName { get; set; }
        public bool IncludeDescription { get; set; }
        public bool IncludeAddress { get; set; }

    }
}

And the folloiwng model class:-

namespace MvcApplication4.Models
{
    public class CsvResult : ExportAccountsResult
    {
        public CsvResult(IEnumerable<Account> accounts, ExportViewModel exportOptions)
            : base(accounts, exportOptions)
        {
        }

        protected override string ContentType
        {
            get { return "text/csv"; }
        }

        protected override string Filename
        {
            get { return "accounts.csv"; }
        }
    }

}

and the folloiwng model class:-

namespace MvcApplication4.Models
{
    public class XlsResult : ExportAccountsResult
    {
        public XlsResult(IEnumerable<Account> accounts, ExportViewModel exportOptions)
            : base(accounts, exportOptions)
        {
        }

        protected override string ContentType
        {
            get { return "application/vnd.ms-excel"; }
        }

        protected override string Filename
        {
            get { return "accounts.csv"; }
        }
    }
}

And finally the folloiwng model class:-

namespace MvcApplication4.Models
{
    public class SelectedCustomers
    {
        public IEnumerable<Account> Info { get; set; }
    }
    public static class ActionResultextensions
    {
        public static ActionResult AsCsvResult(this IEnumerable<Account> accounts, ExportViewModel exportOptions)
        {
            return new CsvResult(accounts, exportOptions);
        }

        public static ActionResult AsXlsResult(this IEnumerable<Account> accounts, ExportViewModel exportOptions)
        {
            return new XlsResult(accounts, exportOptions);
        }
    }
}

But when i run the application i got the following exception :-

System.NullReferenceException was unhandled by user code
  HResult=-2147467261
  Message=Object reference not set to an instance of an object.
  Source=MvcApplication4
  StackTrace:
       at MvcApplication4.Models.ExportAccountsResult.ExecuteResult(ControllerContext context) in c:\Users\Administrator\Documents\Visual Studio 2012\Projects\MvcApplication4\MvcApplication4\Models\ExportAccountResult.cs:line 43
       at System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult)
       at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19()
       at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation)
  InnerException: 

on this code inside the ExportAccountResult.cs:-

foreach (var account in this.Accounts)

So what might be getting wrong?
BR

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-16T18:25:43+00:00Added an answer on June 16, 2026 at 6:25 pm

    You could put the records into a form and make the 2 links submit buttons. Let’s take an example. We will use CSV for both the text file and Excel file format because Excel understands CSV. If you need to apply some special formatting for the Excel export you will could use a third party library such as OpenXML.

    Let’s start by defining our view models:

    public class SelectedCustomers
    {
        public IEnumerable<Account> Info { get; set; }
    }
    
    public class Account
    {
        public string Name { get; set; }
        public string Description { get; set; }
        public string Address { get; set; }
    }
    
    public class ExportViewModel
    {
        public string Format { get; set; }
        public bool IncludeName { get; set; }
        public bool IncludeDescription { get; set; }
        public bool IncludeAddress { get; set; }
    }
    

    then we could have a controller with 2 actions – one that renders the records on the view and one that exports them:

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            var model = new SelectedCustomers
            {
                Info = GetAccounts()
            };
            return View(model);
        }
    
        [HttpPost]
        public ActionResult Export(ExportViewModel exportOptions)
        {
            var accounts = GetAccounts();
            if (exportOptions.Format == "csv")
            {
                return accounts.AsCsvResult(exportOptions);
            }
            else if (exportOptions.Format == "xls")
            {
                return accounts.AsXlsResult(exportOptions);
            }
    
            throw new NotSupportedException(
                string.Format("Unsupported format: {0}", exportOptions.Format)    
            );
        }
    
        private static IEnumerable<Account> GetAccounts()
        {
            // TODO: those records will probably come from a database or something
            // I have hardcoded them here to make my answer more clear
            // and not dependent on some data stores
            return Enumerable.Range(1, 5).Select(x => new Account
            {
                Name = "name " + x,
                Description = "description " + x,
                Address = "address " + x
            });
        }
    }
    

    then we define the corresponding view:

    @model SelectedCustomers
    
    <h3>Select Customers Detials</h3>
    
    @using (Html.BeginForm("Export", null))
    {
        <table>
            <tr>
                <th>
                    NAME @Html.CheckBox("IncludeName", true)
                </th>
                <th>
                    Description @Html.CheckBox("IncludeDescription", true)
                </th>
                <th>
                    Address @Html.CheckBox("IncludeAddress", true)
                </th>
            </tr>
            @foreach (var item in Model.Info) {
                <tr>
                    <td>
                        @Html.DisplayFor(modelItem => item.Name)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.Description)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.Address)
                    </td>
                </tr>
            }
        </table>
    
        <p>
            @Html.ActionLink("Back","customer","Home") |
            <button type="submit" name="format" value="xls">extract to excel</button> |
            <button type="submit" name="format" value="csv">extract to text file</button>
        </p>
    }
    

    Next we implement the custom extension methods used in the controller that return the 2 custom action results:

    public static class ActionResultextensions
    {
        public static ActionResult AsCsvResult(this IEnumerable<Account> accounts, ExportViewModel exportOptions)
        {
            return new CsvResult(accounts, exportOptions);
        }
    
        public static ActionResult AsXlsResult(this IEnumerable<Account> accounts, ExportViewModel exportOptions)
        {
            return new XlsResult(accounts, exportOptions);
        }
    }
    

    And the last part of course is to define the CsvResult and XlsResult custom action results. Since we will be using CSV in both cases we could have a base class:

    public abstract class ExportAccountsResult : ActionResult
    {
        protected ExportAccountsResult(IEnumerable<Account> accounts, ExportViewModel exportOptions)
        {
            this.Accounts = accounts;
            this.ExportOptions = exportOptions;
        }
    
        protected IEnumerable<Account> Accounts { get; private set; }
        protected ExportViewModel ExportOptions { get; private set; }
    
        protected abstract string ContentType { get; }
        protected abstract string Filename { get; }
    
        public override void ExecuteResult(ControllerContext context)
        {
            var response = context.HttpContext.Response;
            response.ContentType = ContentType;
            var cd = new ContentDisposition
            {
                FileName = this.Filename,
                Inline = false
            };
            response.AddHeader("Content-Disposition", cd.ToString());
    
            // TODO: Use a real CSV parser here such as https://github.com/JoshClose/CsvHelper/wiki/Basics
            // and never roll your own parser as shown in this oversimplified
            // example. Here's why: http://secretgeek.net/csv_trouble.asp
            using (var writer = new StreamWriter(response.OutputStream))
            {
                foreach (var account in this.Accounts)
                {
                    var values = new List<object>();
                    if (this.ExportOptions.IncludeName)
                    {
                        values.Add(account.Name);
                    }
                    if (this.ExportOptions.IncludeDescription)
                    {
                        values.Add(account.Description);
                    }
                    if (this.ExportOptions.IncludeAddress)
                    {
                        values.Add(account.Address);
                    }
                    writer.WriteLine(string.Join(", ", values));
                }
            }
        }
    }
    

    And then we could have the 2 implementations:

    public class CsvResult : ExportAccountsResult
    {
        public CsvResult(IEnumerable<Account> accounts, ExportViewModel exportOptions)
            : base(accounts, exportOptions)
        {
        }
    
        protected override string ContentType
        {
            get { return "text/csv"; }
        }
    
        protected override string Filename
        {
            get { return "accounts.csv"; }
        }
    }
    
    public class XlsResult : ExportAccountsResult
    {
        public XlsResult(IEnumerable<Account> accounts, ExportViewModel exportOptions)
            : base(accounts, exportOptions)
        {
        }
    
        protected override string ContentType
        {
            get { return "application/vnd.ms-excel"; }
        }
    
        protected override string Filename
        {
            get { return "accounts.csv"; }
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have the following View inside my ASP.Net mvc 3 web application:- @model IEnumerable<MvcApplication4.Models.Account>
I have the following view inside my asp.net MVC web application:- <table id=tablelist border=1>
I have the following view inside my asp.net mvc application:- @model MvcApplication4.Models.ContactsDetails <h3>Select Contacts
i have the following script inside my asp.net MVC application to bounce the image
i have the following Ajax.beginform inside my asp.net mvc view, where the result of
i have the following script inside my asp.net mvc view:- function disableform(id) { $('#'
I have the following view definition in my asp.net mvc website: <% Using Ajax.BeginForm(UsrCtlChangePassword,
I am working on an asp.net mvc web application and i have the folloiwng
i have the folloiwng action method inside my asp.net mvc application:- public ActionResult CustomersDetails(long[]
I have the following situation: There is one custom view inside of the first

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.