loremIpsum1771
loremIpsum1771

Reputation: 2527

How to render controller data in asp. net view

I have a web app in which has the following features:

  1. Extract data from an MS Excel file
  2. Process the data and store it in data structures based on certain criteria.
  3. Pass the data structures from the controller to the view where they can be rendered.

The issue I'm having occurs with the first few steps. On my view page, I have a button where the user can upload the excel file. Once they click submit, a POST request is sent to transmit the file to the controller action (I'm using the index action for this which I'm not sure is correct) where the data is extracted from the file. Once the file is processed, I want to display the extracted data back on the same page as the upload button.

I've tried to implement this first by creating a class in the controller which is instantiated for each excel row and then each row is stored in one of three different lists of objects.

I then stored each of these lists in the ViewBag object:

    //Handle POST request and determine in the file uploaded was of correct type

 List<Dictionary<string, string>> dictionary = new List<Dictionary<string, string>>();
            bool isSuccess = true;
            int colID = 0;
            int colTier = 0;
            if (Request != null)
            {
                HttpPostedFileBase file = Request.Files["UploadedFile"];

                if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName))
                {
                    string fileName = "";
                    //string fileinitPath = "//app235wnd1t/equityfrontoffice/INGDS/TierBulkUpload/";
                    string fileinitPath = "C:/Users/chawtho/Desktop/";
                    Regex regex = new Regex("WTDA.+xlsx"); //find correct filename
  if (match.Success)
                {
                    fileName = (match.Value);
                }
                if (fileName != "")
                {

               Match match = regex.Match(file.FileName);
                //Extract data from excel file and store in collections
    ViewBag.inactive_subscriptions = inactiveSubscriptions;
    ViewBag.active_subscriptions = activeSubscriptions;
  }
     return View();
   }

In the view I have the following:

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title></title>
</head>
<body>
    random text


    @using (Html.BeginForm("Index", "Subscription", FormMethod.Post, new { enctype = "multipart/form-data" })) { 
    <fieldset class="form">
        <legend>Upload Document</legend>
        <input type="file" name="UploadedFile" id="FileUpload" required />
        <input type="submit" name="Submit" value="Upload" />
        <label id="saveStatus" style="color: red">  
        </label>
    </fieldset>
    }

    @{ 
        <li>@ViewBag.inactive_subscriptions[0].ID</li>
    }

Here, I'm simply trying to read the ID field of the first object in the list of Subscriptions but I get the error:

Cannot perform runtime binding on a null reference

I'm not sure where this error is coming from because when I debug the controller code, the Viewbag is populated with the two lists before the View() is returned. I also tried moving the Subscription Class from the controller to a model class and created a container to hold the list of subscriptions but that didn't resolve the issue.

I think the problem might have something to do with the fact that the code the print the viewbag data is present when the page initially loads but I'm not sure if/how it should be kept from running until the file is processed.

How should I go about structuring this mvc setup to implement what I have outlined?

Upvotes: 0

Views: 355

Answers (1)

Mitch3091
Mitch3091

Reputation: 4688

I put the next example, this is the way that I use to manipulate the excel files, notice that I don't use viewbag variables, this could be an option, like I've said I return the processed data into a json object and then I manipullate it via javascript.

-- Razor ViewPage

<!--Upload File-->
@using (Html.BeginForm("ProcessExcelFile", "ControllerName", FormMethod.Post, 
    new { id = "formUploadExcel", enctype = "multipart/form-data" })) 
{ 
  <div class="row">
      <div class="col-md-4">
          <label for="file">Excel File (.xls, .xlsx)</label>
          <input type="file" name="file" id="file" required="required">

      </div>
  </div>
  <br>
  <button type="submit" class="btn btn-primary">Upload File</button>
}

-- JS Script

<script type="text/javascript">
    $('form#formUploadExcel').unbind('submit').bind('submit', function () {
        formdata = new FormData($('form#formUploadExcel').get(0));
        $.ajax({
            url: this.action,
            type: this.method,
            cache: false,
            processData: false,
            contentType: false,
            data: formdata,
            success: function (data, status) {
                console.log(data);
            },
            complete: function () {
                //code...
            }
        });
        return false;
    });
 </script>

-- Controller

[HttpPost]
public JsonResult ProcessExcelFile(HttpPostedFileBase file)
{
    // Process the excel... 
  var business = new BusinessLayer();
  var data = business.ValidateExcel(file);

  // Return the Json with the procced excel data.
  return Json(data, JsonRequestBehavior.AllowGet);
}

Upvotes: 1

Related Questions