How to add a button to remove user - html

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>

Related

How to send static html data over a web api in asp.net?

I have a product page developed in ASP.NET which I hard coded the values of the products and at the moment is just frontend. On this page, I have product information like Product name and price and a Add to cart button below these items on the page. I have a web api which I would like to send this product information over. For test purposes, it works when I am using an input form but I will like to know how to send these static info like name and the price when I click the button. Below is my html page
<div class="col-md-3 col-sm-3 col-xs-6" style="margin-bottom: 8px;">
<div class="img-thumbnail product-item" style="height: 300px;">
<img class="img-fluid" title="Click to View Product detail" style="cursor: pointer; height: 160px; width: 100%;" src="~/Images/SamsungNote.JPG" />
<div class="caption">
<h5>Samsung note 10 plus</h5>
<p>€ 1071.28</p>
<p>
Available <button class="pull-right" href="#"><i class="fa fa-shopping-cart"> Add to cart</i></button>
</p>
<div class="product-item-badge">New</div>
</div>
</div>
</div>
And In my HomeController, I have the following. Like I said earlier, this works with forms but is there any way i can send this product info when I click on the Add to cart button?
[HttpPost]
public ActionResult AddToCart(Product product)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:60036/");
var content = new StringContent(
JsonConvert.SerializeObject(product),
Encoding.UTF8,
MediaTypeNames.Application.Json);
var postTask = client.PostAsync("api/Product", content);
var result = postTask.Result;
if (result.IsSuccessStatusCode)
{
return this.RedirectToAction("Home");
}
}
this.ModelState.AddModelError(string.Empty, "Server error. Please contact your administrator");
return RedirectToAction("Privacy", "Home");
}
You could use JQuery to find the <h5> and <p> elements and get the product information, and then use Ajax method to submit the data to the action method:
Sample code as below:
<div class="col-md-6 col-sm-6 col-xs-6" style="margin-bottom: 8px;">
<div class="img-thumbnail product-item" style="height: 300px;">
<img class="img-fluid" title="Click to View Product detail" style="cursor: pointer; height: 160px; width: 100%;" src="~/images/Image1.jpg" />
<div class="caption">
<h5>Samsung note 10 plus</h5>
<p>€ 1071.28</p>
<p>
Available <button class="pull-right btn-addToCart" href="#"><i class="fa fa-shopping-cart"> Add to cart</i></button>
</p>
<div class="product-item-badge">New</div>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(function () {
$(".btn-addToCart").click(function () {
//prevent the default event.
event.preventDefault();
//create a object to store the entered value.
var Product = {};
//using jquery to get the product information.
Product.ProductName = $(this).closest(".caption").find("h5").html();
Product.Price = $(this).closest(".caption").find("p:first").html();
$.ajax({
type: "POST",
url: "/Home/AddToCart", //remember change the controller to your owns.
data: Product,
success: function (data) {
console.log(data)
},
error: function (response) {
console.log(response.responseText);
}
});
});
});
</script>
Then, the debugger screenshot like this:
Edit:
The Product model:
public class Product
{
public string ProductName { get; set; }
public string Price { get; set; }
}
Use some JS library (like jQuery) to do AJAX.
For example:
$.ajax({
url: 'http://yourdomain/Home/AddToCart',
data: {'ProductName': 'Samsung', 'Price': 1071.28},
type: "POST",
dataType: "json",
contentType: "application/json;charset=utf-8",
success: function(returnData){
console.log(returnData);
},
error: function(xhr, ajaxOptions, thrownError){
console.log(xhr.status);
console.log(thrownError);
}
});

Ajax doesnt hit controller action

lam trying to save replycomments to the database
here is my html form,
<div id="replyform" class="card my-4 d-none">
<h5 class="card-header">Cevap Yaz:</h5>
<div class="card-body">
<form>
<div class="form-group">
<textarea id="replytext" name="replytext" typeof="text" class="form-control" rows="3"></textarea>
</div>
<button type="submit" id="sendreply" name="sendreply" class="btn btn-primary">Cevap Yaz</button>
</form>
</div>
</div>
and here is my homecontroller action code
public JsonResult ReplyComment(string replycomment, int articleid,int commentid)
{
var UserId = Session["UserId"];
if (replycomment == null)
{
return Json(true, JsonRequestBehavior.AllowGet);
}
db.ReplyComments.Add(new ReplyComment
{ UserId = Convert.ToInt32(UserId), ArticleId = articleid, CommentId=commentid, Paragraph = replycomment, Date = DateTime.Now });
db.SaveChanges();
return Json(false, JsonRequestBehavior.AllowGet);
}
and my ajax code is here
<script type="text/javascript">
$(document).ready(function () {
$("#sendreply").click(function () {
var r_comment = $("#replytext").val();
var r_commentid = $(".astar").val();
$.ajax({
cache: false,
url: '#Url.Action("ReplyComment","Home")',
contentType: "application/json; charset=utf-8",
data: { replycomment: r_comment, articleid:#Model.ArticleId, commentid: r_commentid },
type: 'POST',
dataType: 'json',
success: function (data) {
alert("İşlemOkey");
}
});
});
})
l cant call the Replycomment action with this code
I have tested this code and it will work for you. since am posting via ajax, i have removed the form tags from the body of the html.
For backend(php), I just test it by sending variables r_comment and r_commentid and it works fine. it should work with your backend code now. Give me a shout if it works for you...........
<html>
<head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#sendreply").click(function () {
var r_comment = $("#replytext").val();
var r_commentid = $(".astar").val();
var articleid = '20';
/* lets test with data
var r_comment ='my comment';
var r_commentid = '20';
*/
$('#loader').fadeIn(400).html('Data is being processed');
// assuming that you want query result by posting a variable
var datasend = "r_comment="+ r_comment + "&r_commentid=" + r_commentid + "&articleid=" + articleid;
$.ajax({
type:'POST',
url:'smoke1.php',
data:datasend,
crossDomain: true,
cache:false,
success:function(msg){
//display image loader or text to alert the use that content is being processed
$('#loader').hide();
// and display result
alert("İşlemOkey");
$('#result').fadeIn('slow').prepend(msg);
}
});
})
});
</script>
<div id="replyform" class="card my-4 d-none">
<h5 class="card-header">Cevap Yaz:</h5>
<div class="card-body">
<div class="form-group">
replytext: <textarea id="replytext" name="replytext" class="form-control" rows="3"></textarea>
</div>
<div class="form-group">
astar: <input type="text" class="astar">
</div>
<div id="loader"></div>
<div id="result"></div>
<br>
<button type="submit" id="sendreply" name="sendreply" class="btn btn-primary">Cevap Yaz</button>
</div>
</div>
</body></html>
my testing backend in php(Try it with yoour backend code)
smoke1.php
<?php
echo "ok";
echo $_POST['r_comment'];
echo $_POST['r_commentid'];
echo $_POST['articleid'];
?>

Open bootstrap Modal from link for each item in a list in view - MVC

I have a view which does a for each loop over a list of database items. I am looking to have a "Details" action for each one which opens a modal passing the id for each item into it and displays the details for that item in a partial view within that modal.
So far I have the following
#foreach (var item in Model)
{
Details
}
<div class="modal fade" id="detailsModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body">
#{Html.RenderAction("_PartialDetails", "ActivityAds", new { #id = "NEED TO PASS ID HERE" });}
</div>
</div>
</div>
</div>
I am trying to avoid putting the modal in the for each loop as I fear that would be very inefficient having to create a modal for every record. I could be calling the partial view in the Modal wrong as well. I am out of practise Im afraid and I am sure there is a way to do this
Thank you
One way would be to use ajax to fill in the container dynamically.
here is an example from an app i have - note that some of the javascript is in an external js file so can't directly use model; model values are stored in hidden fields and/or data-id, data-value attributes for this purpose
#foreach (var assignment in Model.Assignments)
{
<li role="presentation" id="assignmentsDetails_#assignment.AssignmentView.AssignmentViewId" data-id="#assignment.AssignmentView.AssignmentViewId">
<a role="menuitem" onclick="selectCriteria(this);" title="#assignment.AssignmentView.AssignmentViewDescription">Criteria #criteriaNumber</a>
</li>
criteriaNumber++;
}
javascript
function selectCriteria(clickedElement) {
var dataid = $(clickedElement).parent().attr("data-id");
loadAssignmentDetails(dataid);
}
function loadAssignmentDetails(assignmentViewId) {
$.ajax({
type: "GET",
url: Config.RootUrl + "Assignments/Detail/" + assignmentViewId + "/" + $("#AssignmentTypeValueId").val(),
success: function (data) {
$("#assignmentViewDetailsContainer").html(data);
}
});
}
Here is my solution based "Nikki9696" answer :) It works perfectly. Thank you very much! Nikki9696
function showDetails(clickedElement) {
var dataid = $(clickedElement).attr("data-id");
showDetailsAjax(dataid);
}
function showDetailsAjax(activityAdID) {
var link = '#Url.Action("_PartialDetails", "ActivityAds", new { id = "-1"})'
link = link.replace("-1", activityAdID);
$.ajax({
type: "GET",
url: link,
error: function(data)
{},
success: function (data) {
$("#detailsModal .modal-body").html(data);
$('#detailsModal').modal('show');
},
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class="modal fade" id="detailsModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body"></div>
</div>
</div>
</div>
#foreach (var item in Model)
{
<a onclick="showDetails(this);" id="activityAdDetails_#item.ad_id" data-id="#item.ad_id">Details</a>
}
I have an alternative, similar but different enough that I thought it worth sharing - I wanted to use unobtrusive jquery to achieve the same thing through attribute mark up only, so I define a separate partial view for the modal and it's script, and include it in my layout page, so that in each other view all I need to do is add markup to use the modal and functionality I built into that partial script. I've added functionality to the modal to allow me to specify a script to call when the modals submit is successful, etc. The dialog content is retrieved from the server (by calling a controller method that returns a partial view - hence the need to disable ajax cache). Heres an example outside of a list which calls the javascript RefreshAll when done:
<button class="btn btn-sm btn-success completeFixtureButton"
data-submittext="Update"
data-modalsubmit="CompleteFixtureForm"
data-modaltitle="Fixture Completed"
data-modalsuccess="RefreshAll();"
data-modalload="#Url.Action("FixtureCompleted", new { fixtureId = fix.Id })">
and here's a similar example but from a link styled as a button instead of a button:
<a class="btn btn-default" href="#"
data-modalsubmit="editLeagueForm"
data-modaltitle="Edit Season"
data-modalsize="lg"
data-modalload="#Url.Action("EditLeaguePartial", "League", new { leagueId = Model.Season.League.Id, seasonId = Model.Season.Id })"><span class="glyphicon glyphicon-white glyphicon-cog"></span>Season Settings</a>
Heres one within a list/table:
<tbody id="clubList">
#foreach (Player p in Model.Club.Players.OrderBy(p => p.LastName))
{
bool playerManager = Model.Club.Managers.Any(m => m.Id == p.Id);
<tr>
<td>
<a href='#' data-modaltitle="#p.FullName" data-modalload="#Url.Action("ContactPlayerPartial", "Player", new { playerId = p.Id })">
<img src="#Url.Action("ProfilePictureById", "Player", new { playerId = p.Id })" style="max-width:3em; margin-right:10px;" class="pull-left" /> #p.FullName
</a>
</td>
</tr>
...
}
and here's the modal partial (_ModalDialogPartial.cshtml) in the Shared Views folder:
<div id="details" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h2 id="detailsHeader"></h2>
</div>
<div class="modal-body">
<div id="detailsBody" ></div>
</div>
<div class="modal-footer">
Close
<input type="submit" id="btnModalSave" class="btn btn-primary" value="Save"/>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$.ajaxSetup({ cache: false });
initialiseModals();
});
function initialiseModals() {
$('#details').on('shown.bs.modal', function () {
$.validator.unobtrusive.parse($('#details'));
});
$(document).on('click', '*[data-modalload]', function () {
var e = $(this);
if (e.data('submittext') != undefined) {
$('#btnModalSave').html(e.data('submittext'));
} else $('#btnModalSave').html('Save');
if (e.data('class') != undefined) {
var cls = e.data('class');
$('#details').removeClass(cls).addClass(cls);
}
if(e.data('modalsize') != undefined) {
var size = e.data('modalsize');
$('.modal-dialog').addClass('modal-' + size);
}
if (e.data('modalsubmit') == undefined) {
$('#btnModalSave').hide();
$('#btnModalCancel').addClass("btn-primary");
}
else {
$('#btnModalSave').show();
$('#btnModalCancel').removeClass("btn-primary");
$('#btnModalSave').unbind('click').click(function (ctrl) {
$('#btnModalSave').attr('disabled', 'disabled');
ctrl.preventDefault();
var submitUrl = $('#' + e.data('modalsubmit')).attr("action");
var formData = $('#' + e.data('modalsubmit')).serialize();
$.post(submitUrl,
formData,
function (data, status, xhr) {
$('#btnModalSave').removeAttr('disabled');
$('#details').modal('hide');
if (e.data('modalsuccess') != undefined) {
eval(e.data('modalsuccess'));
}
}).error(function () {
$('#btnModalSave').prop('disabled', false);
});
});
}
$('#detailsBody').load(e.data('modalload'), function () {
$('#detailsHeader').html(e.data('modaltitle'));
$('#details').modal('show');
$.validator.unobtrusive.parse($('#detailsBody'));
});
});
}
</script>

"[object object]" shown when double-clicking input

Below is the template I am using for the directive. In code we are
fetching the data from a service in that data we have all the
information of that particular person. And from that data we are
showing only first name, last name and designtion or company
affiliation.
<div ng-if="model" class="entry-added">
<span class="form-control"><b>{{model.fullName}}</b>, <br/><span class="small-font">{{(model.designation)?model.designation:model.companyAffiliation}}</span></span>
<a ng-click="removePerson()" class="action-remove"><i class="fa fa-remove"></i></a>
</div>
<div ng-show="!model" class="input-group">
<input type="text"
class="form-control"
name="{{name}}"
id="{{name}}"
placeholder="{{placeholder}}"
ng-required="{{isRequired}}"
typeahead-on-select = "change($item, $model, $label)"
ng-model="model"
typeahead-min-length="3",
typeahead="suggestion for suggestion in searchEmployees($viewValue)"
typeahead-template-url="typeAheadTemplate.html"
typeahead-loading="searching"
typeahead-editable="false">
<script type="text/ng-template" id="typeAheadTemplate.html">
<a class="ui-corner-all dropdown" tabindex="-1">
<div class="col-md-2"><img class="dropdown-image" ng-src="https://people.***.com/Photos?empno={{match.model.employeeNumber}}"></div>
<div>
<div bind-html-unsafe="match.model.fullName"></div>
<div bind-html-unsafe="match.model.designation"></div>
</div>
</a>
</script>
I am using a custom directive to display a search field. The drop down is displaying [object object].
Directive
// In backend taxDeptContact is a Person type object
/*
Directive code
*/
(function () {
'use strict';
angular.module('treasuryApp.directives').directive('employeeSearch', employeeSearch);
employeeSearch.$inject = ['$resource', '$rootScope', 'ErrorHandler'];
function employeeSearch($resource, $rootScope, ErrorHandler) {
return {
restrict: 'E',
require: '^form',
scope: {
model: "=",
isRequired: '#',
submitted: "=",
onSelect: '&',
name: '#',
index:'#'
},
link: function(scope, el, attrs, formCtrl) {
//set required attribute for dynamically changing validations
scope.searchEmployees = function (searchTerm) {
var users = [];
var myResult = [];
var result = $resource($rootScope.REST_URL + "/user/getEmployees", {term: searchTerm}).query().$promise.then(function (value) {
//console.log(value)
$.each(value, function(i, o) {
users.push(o);
});
return users;
});
return result;
}
scope.removePerson = function() {
scope.model=null;
}
scope.userNotSelectedFromTypeahead = function(name) {
if(undefined === formCtrl[name]) {
return false;
}
return formCtrl[name].$error.editable;
};
scope.change = function(item, model, label) {
scope.model = item
scope.onSelect(
{name: scope.name, person: scope.model});
},
templateUrl: 'app/components/common/directives/employee-search.tpl.html'
};
}
})();
View that is using the directive
<div class="form-group">
<label class="col-sm-3>Tax Dept Contact</label>
<div class="col-sm-4">
<employee-search model="reqCtrl.requestObj.taxDepartmentContact" name="taxDeptContact" is-required="false" submitted="reqCtrl.submitted"/>
</div>
</div>
Image of the error occuring
Looks like this may be your trouble spot
typeahead="suggestion for suggestion in searchEmployees($viewValue)"
suggestion for suggestion is pulling the whole object. Have you tried displaying a particular attribute of suggestion?
For example: if you had a suggestion.name attribute you would write:
typeahead="suggestion.name for suggestion in searchEmployees($viewValue)"
Finally got the answer: I used autocomplete="off" in my directive and thats all
<input type="text" autocomplete="off" />

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

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