MVC 5 - JSON post to controller always is null on controller side - json

I've looked for a couple hours now, hoping not to duplicate a question, and I just can't find what I'm looking for.
I am working on passing a complex object back from a form to a controller, and having it parse everything out. The problem I get is the controller shows a null input, despite the header post from Chrome showing the data going out. Can anyone give me a hand? I've included code below.
Model
public class QuizTakenObject
{
[NotMapped]
public QuizTakenComplete quizTakenComplete { get; set; }
[NotMapped]
public List<QuizSubmittedAnswers> submittedAnswers { get; set; }
[NotMapped]
public TopicList Topic { get; set; }
[NotMapped]
public QuizHeader QuizHeader { get; set; }
}
View/Script
#model App.Models.QuizTakenObject
#{
ViewBag.Title = "Take Quiz";
}
#section pageScripts{
<script type="text/javascript">
$(document).ready(function () {
//Highlight background of selected background for increased visibility
$("input[name^=QuizSubmittedAnswer]").change(function () {
$(this).parent().addClass("bg-primary");
$(this).parent().siblings().removeClass("bg-primary");
});
//Show save prompt on page after one answer is picked
var i = 0;
if (i == 0) {
$("input[name^=QuizSubmittedAnswer]").change(function () {
$("#quizSave").fadeIn('fast');
$("#quizSave").animate({ height: '125px' }, 'fast')
.animate({ width: '250px' }, 'fast', function () {
$("#quizSaveText").fadeIn('500');
});
});
}
//Prevent submitting before all answers have been selected
//Count all questions, one per form group
var questionsCount = $("form-group").length;
//Listen for answers to be selected
$("input[name^=QuizSubmittedAnswer]").change(function () {
//Check to see if all answers are selected
if ($("input[name^=QuizSubmittedAnswer]:checked").length >= questionsCount) {
$("#saveAndSubmitQuizButton").removeClass("disabled");
}
});
//Save and submit quiz
$("#saveAndSubmitQuizButton").click(function () {
event.preventDefault;
var complete = true;
saveQuizAttempt(complete);
});
//Save but not submit quiz
$("#saveQuizOnlyButton").click(function () {
event.preventDefault;
var complete = false;
saveQuizAttempt(complete);
});
//Create or update quiz attempt in DB
//saveQuizAttempt complete indicates if the record is to be marked as final
function saveQuizAttempt(complete) {
var array = $("#takeQuizForm").serializeArray();
//build JSON array
var json = {};
$.each(array, function () {
json[this.name] = this.value || '';
})
//array.push({ "IsComplete": complete });
//AJAX to post data
$.ajax({
type: "POST",
url: "SubmitQuiz",
data: JSON.stringify(array),
dataType: "json",
contentType:"application/json; charset=UTF-8",
success: function (data) {
console.log("Success!");
},
error: function () {
console.log("Error");
}
});
}
});
</script>
}
<style>
#quizSave {
display: none;
position: fixed;
z-index: 999;
height: 0;
width: 0;
bottom: 100px;
right: 0;
background-color: khaki;
border: 1px solid black;
border-radius: 2px 2px 2px 2px;
padding: .5em 1em .5em 1em;
}
</style>
<h2>#ViewBag.TopicName Quiz</h2>
<div class="row">
<div class="container col-xs-9 col-sm-9 col-md-9 col-lg-9">
<div class="well well-sm">
<strong>Directions:</strong> #Model.QuizHeader.QuizSummary
</div>
#using (Html.BeginForm("SubmitQuiz", "Quiz", FormMethod.Post, new { id = "takeQuizForm" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.QuizHeader.QuizID)
#Html.HiddenFor(model => model.QuizHeader.TopicID);
<input type="hidden" name="QuizTakenComplete.UserID" id="QuizTakenComplete.UserID" value="#(ViewBag.UserID)" />
<input type="hidden" name="QuizTakenComplete.IsComplete" id="QuizTakenComplete.IsComplete" value="false" />
<!--Questions/Answers-->
for (int i = 0; i < #Model.QuizHeader.QuizQuestions.Count(); i++)
{
<div class="quizQuestionBlock#(i)">
<hr />
<h4>#Model.QuizHeader.QuizQuestions.ElementAt(i).Question</h4>
<form-group>
<input type="hidden" name="QuizSubmittedAnswers[#(i)].QuestionID" id="QuizSubmittedAnswers[#(i)].QuestionID" value="#(Model.QuizHeader.QuizQuestions.ElementAt(i).QuestionID)">
#{for (int j = 0; j < Model.QuizHeader.QuizQuestions.ElementAt(i).QuizAnswers.Count(); j++)
{
<!--answers via radio buttons-->
<div id="answer#(j)#(i)" class="quizAnswer#(j)">
<input type="radio" class="individualQuizAnswer" name="QuizSubmittedAnswers[#(i)].AnswerID" value="#Model.QuizHeader.QuizQuestions.ElementAt(i).QuizAnswers.ElementAt(j).AnswerID"> #Model.QuizHeader.QuizQuestions.ElementAt(i).QuizAnswers.ElementAt(j).Answer
</div>
}
}
</form-group>
</div>
}
<hr />
<button class="btn btn-success btn-block disabled" id="saveAndSubmitQuizButton" type="button">submit quiz</button>
<div style="text-align:center;">
<small> Submitting quiz will finalize this attempt and update your score records.</small>
</div>
<br />
<br />
}
</div>
<!--Sidebar-->
<div class="container col-xs-3 col-sm-3 col-md-3 col-lg-3">
<div class="panel panel-default">
<div class="panel-heading collapsable">
<h5><span class="glyphicon glyphicon-cog"></span> Actions</h5>
</div>
<div class="panel-body">
<span class="glyphicon glyphicon-backward"></span> #Html.ActionLink("return to library", "Index", new { controller = "Library" })<br />
#Html.ActionLink("cancel/go home", "Index", new { controller = "Home" }, new { #style = "color:red;" })
</div>
</div>
</div>
<!--Quiz Save/Quit-->
<div id="quizSave">
<div id="quizSaveText" style="display:none;">
Save current answers and return to App training/quiz library?<br />
<button type="button" id="saveQuizOnlyButton" class="btn btn-success">yes</button>
<button type="button" data-toggle="tooltip" class="btn btn-danger" title="this will cancel all previous work without saving and return to the main menu">no</button>
<br />
<small>You will be able to return later to resume your work.</small>
</div>
</div>
</div>
Controller
//POST: Quiz/SubmitQuiz
[HttpPost]
public async Task<ActionResult> SubmitQuiz(string quizObject)
{
//Send false value for complete in AJAX call, just parse based on this
//Two starting JS scripts, which flow into a unified function
var input = new JavaScriptSerializer().Deserialize<QuizTakenObject>(quizObject);
var quizTakenComplete = new QuizTakenComplete
{
UserID = input.quizTakenComplete.UserID,
IsComplete = input.quizTakenComplete.IsComplete,
LastUpdate = DateTime.Now
};
//Parse if complete for purposes of updating records.
if (quizTakenComplete.UserID != null || quizTakenComplete.UserID != "")
{
db.QuizTakenComplete.Add(quizTakenComplete);
await db.SaveChangesAsync();
var quizAttemptID = quizTakenComplete.QuizAttemptID;
//Now Add Each Answer
var quizTaken = new QuizSubmittedAnswers();
quizTaken.QuizAttemptID = quizAttemptID;
quizTaken.TopicID = input.Topic.TopicID;
quizTaken.QuizID = input.QuizHeader.QuizID;
return Content("Saved");
}
else
{
return Content("Not Saved");
}
}

I think that the problem is in Ajax Call you didn't specify the attribute name
try with this
$.ajax({
type: "POST",
url: "SubmitQuiz",
data: {quizObject : JSON.stringify(array)},
dataType: "json",
contentType:"application/json; charset=UTF-8",
success: function (data) {
console.log("Success!");
},
error: function () {
console.log("Error");
}
});

Related

How to add a button to remove user

I currently have this code that displays users on a team and when you click on the name of a user that is on the list it passes the name that you click to a function which removes them from the team. Instead I would like a button to be next to the name and when you click the button it removes the person that the button is next to. How would I go about doing this
$(document).ready(function() {
$("#your_teams234").change(function() {
var team = $("#your_teams234").val();
$.ajax({
url: 'functions.php',
method: 'post',
data: 'members=' + team
}).done(function(requests) {
console.log(requests);
requests = JSON.parse(requests);
$('#teammates').empty();
if (requests.length != 0) {
$("#teamContainer").css("display", "block");
requests.forEach(function(request) {
$('#teammates').append('<p class="myDivs">' + request.email + '</p>')
})
}
if (requests.length == 0) {
$('#teammates').append(`<p> No teammates </p>`)
}
$('.myDivs').click(function() {
$var1 = $(this).text();
$.ajax({
url: 'functions.php',
type: 'post',
data: {
"callFunc1": $var1,
"teamName": team
},
success: function(response) {
console.log(response);
}
});
});
})
})
})
Here is the html code for my team container
<div id="teamContainer" style="display: none;">
<p style="font-weight: bold; font-size:18px left">Current Team Members (click name to remove)</p>
<div id='teammates'>
</div>
<hr style="margin-left: 350px; margin-right: 350px">
</div>
</div>
First off, you really should be passing ID's rather than names in order to access a user. What if you have 2 users with the same name, or apostrophes/odd characters - or even the lack of a name? At any rate, you didn't show your HTML but here's how it could work.
$('.remover').click(function() {
let $user = $(this).closest('.user-container').find('.myDivs');
let $userid = $user.data('id');
let $username = $user.text();
console.log(`remove user ${$username}, id ${$userid}`);
$(this).closest('.user-container').remove()
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='user-container'>
<span class='myDivs' data-id='1'>John Smith</span>
<button class='remover'>Remove user</button>
</div>
<div class='user-container'>
<span class='myDivs' data-id='2'>Susan Sarandon</span>
<button class='remover'>Remove user</button>
</div>
<div class='user-container'>
<span class='myDivs' data-id='3'>Bill Nye</span>
<button class='remover'>Remove user</button>
</div>

Display contents of SQL Table with Asp.Net Core MVC and FullCalendar

I have setup my app to display events on calendar. However, whilst the correct number of events will display the date and time is always the current date and time rather than what I have input into the SQL db table. Any help with what I am doing wrong would be greatly appreciated. My code is below:
View
#model IEnumerable<wccFacilityBookings.Models.Events>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<div id="calender"></div>
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title"><span id="eventTitle"></span></h4>
</div>
<div class="modal-body">
<p id="pDetails"></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<link href="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.min.css" rel="stylesheet" />
<link href="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.print.css" rel="stylesheet" media="print" />
#section Scripts{
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.min.js"></script>
<script>
$(document).ready(function () {
var events = [];
$.ajax({
type: "GET",
url: "/applications/GetEvents",
success: function (data) {
$.each(data, function (i, v) {
events.push({
title: v.Subject,
description: v.Description,
start: moment(v.Start),
end: v.End != null ? moment(v.End) : null,
color: v.ThemeColor,
allDay : v.IsFullDay
});
})
GenerateCalender(events);
},
error: function (error) {
alert('failed');
}
})
function GenerateCalender(events) {
$('#calender').fullCalendar('destroy');
$('#calender').fullCalendar({
contentHeight: 400,
defaultDate: new Date(),
timeFormat: 'h(:mm)a',
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay,agenda'
},
eventLimit: true,
eventColor: '#378006',
events: events,
eventClick: function (calEvent, jsEvent, view) {
$('#myModal #eventTitle').text(calEvent.title);
var $description = $('<div/>');
$description.append($('<p/>').html('<b>Start:</b>' + calEvent.start.format("DD-
MMM-YYYY HH:mm a")));
if (calEvent.end != null) {
$description.append($('<p/>').html('<b>End:</b>' + calEvent.end.format("DD-
MMM-YYYY HH:mm a")));
}
$description.append($('<p/>').html('<b>Description:</b>' +
calEvent.description));
$('#myModal #pDetails').empty().html($description);
$('#myModal').modal();
}
})
}
})
</script>
}
Controller
// GET: Applications/CalendarView
public IActionResult CalendarView()
{
return View();
}
public JsonResult GetEvents()
{
using (WCCFacilityBookingsContext context = new WCCFacilityBookingsContext())
{
var events =_context.Events.ToList();
return Json(events);
}
}
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace wccFacilityBookings.Models
{
public class Events
{
[Key]
public int EventID { get; set; }
public string Subject { get; set; }
public string Description { get; set; }
public System.DateTime Start { get; set; }
public Nullable<System.DateTime> End { get; set; }
public string ThemeColor { get; set; }
public bool IsFullDay { get; set; }
}
}
Does this have something to do with it being Asp.Net Core?
Yes, in .NET Core 3.x, when you want to pass json from controller to client, it will camel-case all JSON output by default.
To avoid this, you can add the following setting in startup.cs ConfigureServices method:
services.AddMvc()
.AddJsonOptions(opts => opts.JsonSerializerOptions.PropertyNamingPolicy = null);
Since I added this setting before, the problem did not appear when I tested with your code. If I delete it, your problem will be reproduced.
So you have two solutions, change the field name to camel-case in js, or add the above code in startup.
OK, as always #YongquingYu got me on the right track. I am a 'nuffy' when it come to Ajax and Jquery. My issue, for reasons I don't understand was with capitalization, once I made the 'properties' lower case it worked. Does this have something to do with it being Asp.Net Core? Anyway my code (which is working as desired) is below:
#section Scripts{
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.min.js"></script>
<script>
$(document).ready(function () {
var events = [];
$.ajax({
type: "GET",
url: "/Applications/GetEvents",
success: function (data) {
$.each(data, function (i, v) {
events.push({
title: v.applicantContactName,
description: v.facility,
start: moment(v.start),
end: v.end != null ? moment(v.end) : null,
color: v.themeColor,
allDay: v.isFullDay
});
})
GenerateCalender(events);
},
error: function (error) {
alert('failed');
}
})
function GenerateCalender(events) {
$('#calender').fullCalendar('destroy');
$('#calender').fullCalendar({
contentHeight: 400,
defaultDate: new Date(),
timeFormat: 'h(:mm)a',
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay,agenda'
},
eventLimit: true,
eventColor: '#378006',
events: events,
eventClick: function (calEvent, jsEvent, view) {
$('#myModal #eventTitle').text(calEvent.title);
var $description = $('<div/>');
$description.append($('<p/>').html('<b>Start: </b>' + calEvent.start.format("DD-MMM-YYYY HH:mm a")));
if (calEvent.end != null) {
$description.append($('<p/>').html('<b>End: </b>' + calEvent.end.format("DD-MMM-YYYY HH:mm a")));
}
$description.append($('<p/>').html('<b>Description: </b>' +
calEvent.description));
$('#myModal #pDetails').empty().html($description);
$('#myModal').modal();
}
})
}
})
</script>
}
// GET: Applications/CalendarView
public IActionResult CalendarView()
{
return View();
}
public JsonResult GetEvents()
{
using (WCCFacilityBookingsContext context = new WCCFacilityBookingsContext())
{
var events = context.BookingApplications.ToList();
return Json(events);
}
}

can't create new performance in mvc [duplicate]

I have this form:
#model CupCakeUI.Models.CupCakeEditViewModel
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "createFrm" }))
{
<div class="form-group">
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
<input type="text" id="Name" name="Name" value="#Model.Name" />
</div>
<div class="editor-label">
#Html.LabelFor(model => model)
</div>
<div class="editor-field">
<input type="text" id="Price" name="Price" value="#Model.Price" />
</div>
<div class="col-md-offset-2 col-md-10">
<input type="button" id="btnCreate" value="Create" class="btn btn-default" />
</div>
</div>
}
I am trying to use ajax post to send data to the Action Method, however its always receiving empty object. I have done that several times in the past, and now i tried different ways which not working, The code:
$(document).ready(function () {
$("#btnCreate").click(function () {
var name = $("#Name").val();
var price = $("#Price").val();
var cupCakeEditModel = { "CupCakeId": 0, "Name": name, "Price": price };
var json = JSON.stringify(cupCakeEditModel);
$.ajax({
type: 'POST',
url: "/CupCake/Create",
data: JSON.stringify(cupCakeEditModel),
contentType: 'application/json',
success: function () {
alert("succes");
},
error: function () {
alert("error");
}
});
})
})
Its showing this in the console when logging:
This is the Action Method and Class used:
[HttpPost]
public JsonResult Create (CupCakeUI.Models.CupCakeEditViewModel cupCakeEditModel)
{
var cupCake =
CupCakeData.Save(cupCakeEditModel);
return Json("cupCake",
JsonRequestBehavior.AllowGet);
}
This the class:
public class CupCakeEditViewModel
{
public int CupCakeId;
[Display(Name = "CupCake Name")]
public string Name;
public string Price;
}
I have also used this, but not working:
$("#btnCreate").click(function () {
var cupCakeEditModel =
$("#createFrm").serialize();
$.ajax({
url: "/CupCake/Create",
type: "POST",
data: cupCakeEditModel,
success: function (response) {
alert("Success");
},
error: function (response) {
}
});
})
And several answers i found on the forum, but it seems something weird!
You model contains only fields, and the DefaultModelBinder does not bind fields, only properties. Change the model to
public class CupCakeEditViewModel
{
public int CupCakeId { get; set; }
[Display(Name = "CupCake Name")]
public string Name { get; set; }
public string Price { get; set; }
}

Use same input text for two button using ASP.NET MVC

I want to use the same text to go different View.At present I set two view one is PlaceInformation and another is Google Map View. How can I set condition to go both View using HTML Beginfrom.I want to use #using (Html.BeginForm("GoogleMapView", "Home")) here. My Code sample is look like this-
#using (Html.BeginForm("PlaceInformation", "Home"))
{
<div class="wrapper wrapper-content">
<div class="row">
<div class="col-sm-12">
#Html.TextBoxFor(m =>m.Name)
<label for="somevalue">City Name</label>
<div class="input-group-btn">
<button class="btn btn-lg btn-primary" type="submit">Search</button>
</div>
<div class="input-group-btn">
<button class="btn btn-lg btn-primary" type="submit">Map View</button>
</div>
</div>
</div>
</div>
}
This is how i modified code .But it is not working.
<form id="myForm">
<div class="wrapper wrapper-content">
<div class="row">
<div class="col-sm-12">
#Html.TextBoxFor(m => m.Name)
<label for="somevalue">City Name</label>
<div class="input-group-btn">
<button id="searchBtn" class="btn btn-lg btn-primary" type="submit">Search</button>
</div>
<div class="input-group-btn">
<button id="mapViewBtn" class="btn btn-lg btn-primary" type="submit">Map View</button>
</div>
</div>
</div>
</div>
<script> {
$("#searchBtn").on("click", function (event) {
event.preventDefault();
$.ajax({
type: "POST",
url: '/home/placeinformation',
data: $("#myForm").serialize(), // serializes the form's elements.
success: function (data) {
//here you will get the result from the Controllers, like a partial view or you can do a redirect to another view if form post is successful.
},
error: function (xhr, status, error) {
//Handle any errors here
}
});
});
}
</script>
<script>{
$("#mapViewBtn").on("click", function (event) {
event.preventDefault();
$.ajax({
type: "POST",
url: '/home/GoogleMap',
data: $("#myForm").serialize(), // serializes the form's elements.
success: function (data) {
//here you will get the result from the Controllers, like a partial view or you can do a redirect to another view if form post is successful.
},
error: function (xhr, status, error) {
//Handle any errors here
}
});
});
}
</script>
My Controller for GoogleMap is-
public ActionResult GoogleMap(City objCityModel)
{
string name = objCityModel.Name;
ViewBag.Title = name;
var ReadJson = System.IO.File.ReadAllText(Server.MapPath(#"~/App_Data/POI_Json/" + name + ".json"));
RootObject json = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<RootObject>(ReadJson);
List<Poi> mycities = new List<Poi>();
foreach (var item in json.poi)
{
Poi obj = new Poi()
{
Name = item.Name,
Shorttext = item.Shorttext,
GeoCoordinates = item.GeoCoordinates,
Images = item.Images,
};
mycities.Add(obj);
}
ViewBag.Cities = mycities;
return View();
}
For Getting the name-
[HttpPost]
public ActionResult Index(City objCityModel)
{
string name = objCityModel.Name;
return View();
}
in My PLace information I am using the same data as GoogleMap view
public ActionResult PlaceInformation(City objCityModel)
{
string name = objCityModel.Name;
ViewBag.Title = name;
var ReadJson = System.IO.File.ReadAllText(Server.MapPath(#"~/App_Data/POI_Json/" + name + ".json"));
RootObject json = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<RootObject>(ReadJson);
List<Poi> mycities = new List<Poi>();
foreach (var item in json.poi)
{
Poi obj = new Poi()
{
Name = item.Name,
Shorttext = item.Shorttext,
GeoCoordinates = item.GeoCoordinates,
Images = item.Images,
};
mycities.Add(obj);
}
ViewBag.Cities = mycities;
return View();
}
This will only generate one html form and it is the form element that decides where the form is posted. In other words there is no way to post this form to different controller actions depending on the button being clicked. However, there are of course other ways. I would bind and post the two post buttons with jQuery like this:
Change .cshtml to this:
<form id="myForm">
#Html.TextBoxFor(m => m.Name)
<label for="somevalue">City Name</label>
<div class="input-group-btn">
<button id="searchBtn" class="btn btn-lg btn-primary" type="submit">Search</button>
</div>
<div class="input-group-btn">
<button id="mapViewBtn" class="btn btn-lg btn-primary" type="submit">Map View</button>
</div>
</form>
Add id to the buttons:
<div class="input-group-btn">
<button id="searchBtn" class="btn btn-lg btn-primary" type="submit">Search</button>
</div>
<div class="input-group-btn">
<button id="mapViewBtn" class="btn btn-lg btn-primary" type="submit">Map View</button>
</div>
script:
$("#searchBtn").on("click", function (event) {
event.preventDefault();
$.ajax({
type: "POST",
url: '/home/placeinformation',
data: $("#myForm").serialize(), // serializes the form's elements.
success: function (data) {
//here you will get the result from the Controllers, like a partial view or you can do a redirect to another view if form post is successful.
},
error: function (xhr, status, error) {
//Handle any errors here
}
});
});
}
second script (I changed the button you bind to and the controller action you want to call.
$("#mapViewBtn").on("click", function (event) {
event.preventDefault();
$.ajax({
type: "POST",
url: '/home/urlToTheOtherAction,
data: $("#myForm").serialize(), // serializes the form's elements.
success: function (data) {
//here you will get the result from the Controllers, like a partial view or you can do a redirect to another view if form post is successful.
},
error: function (xhr, status, error) {
//Handle any errors here
}
});
});
}

import excel data to database in angularjs

I am trying to read and insert excel file data to mysql database table using angularjs( front and) and codeigniter (back end).thanks in advance
included xlsx-reader.js
this is only the excel file read code it is not working.
HTML
<div ng-app="App">
<div ng-controller="PreviewController">
<div class='form-group'>
<label for='excel_file'>Excel File</label>
<button class="btn btn-link" type="file" ng-model="file"ngf-select ngf-change="importToExcel()">
<span class="glyphicon glyphicon-share"></span>ImportExcel
</button>
</div>
</div>
</div>
app.js
(function(undefined) {
App.factory("XLSXReaderService", ['$q', '$rootScope',
function($q, $rootScope) {
var service = function(data) {
angular.extend(this, data);
};
service.readFile = function(file, showPreview) {
var deferred = $q.defer();
XLSXReader(file, showPreview, function(data){
$rootScope.$apply(function() {
deferred.resolve(data);
});
});
return deferred.promise;
};
return service;
}
]);
}).call(this);
controller.js
angular.module('App').controller('PreviewController', function($scope, XLSXReaderService)
{
$scope.showPreview = false;
$scope.importToExcel= function(files) {
$scope.sheets = [];
$scope.excelFile = file[0];
XLSXReaderService.readFile($scope.excelFile, $scope.showPreview).then(function(xlsxData) {
$scope.sheets = xlsxData.sheets;
});
};
}