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

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

Related

Getting data from Json returned by controller action

I have a modal that I am trying to populate via sending a modal through a JSON obj from a controller action. It seems to be returning the model just fine, however I am having a hard time extracting the data from the model to populate HTML.. Below is my code.
If anyone can help correct my syntax in the JS, it would be greatly appreciated.
Controller action:
[HttpGet]
public ActionResult JobPollerParameters(int jobRequestId)
{
var model = new Dashboard.Web.Models.Tools.JobPollerMonitorResponseModel();
try
{
using (var client = new DashboardAPIClient())
{
var response = client.GetJobRequestParemeters(jobRequestId);
model.JobRequestParameters = response.JobRequestParameters;
}
}
catch (Exception ex)
{
ExceptionHandling.LogException(ex);
throw;
}
return Json( model.JobRequestParameters, JsonRequestBehavior.AllowGet);
}
Modal which JSON data needs to be displayed on:
<div class="modal fade" id="paramsModal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header modal-header-primary">
<a class="btn btn-xs btn-primary pull-right" data-dismiss="modal" aria-label="Close"><span class="glyphicon glyphicon-remove"></span></a>
<h4 class="modal-title" id="modalTitleText"></h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-3 font-weight-bold">Name:</div>
<div class="col-md-9" id="modalName"></div>
</div>
<div class="row">
<div class="col-md-3 font-weight-bold">Message:</div>
<div class="col-md-9 text-break" id="modalMessage"></div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
JS function:
$('#paramModalBtn').click(function () {
var col = $('#requestId');
var jobRequestId = col.data("id");
//console.log(jobRequestId);
$.ajax({
url: '#Url.Action("JobPollerParameters", "Tools")',
data: { "jobRequestId": jobRequestId},
success: function(results){
$modal = $('#paramsModal');
$modal.modal("show");
var name = JSON.parse(results.name);
var message = JSON.parse(results.message)
$('#modalName').text(name);
$('#modalMessage').text(message);
}
});
});
Also for some context, I would like to show that the Model I am returning should be a list of "JobRequestParameters", of which I need Model.JobRequestParameters.Name, and JobRequestParameters.value.
If I log results in the console, I can see what I need is actually there.
JobParameterId: 118190
JobRequestId: 118190
Name: "CUSTOMERTYPE"
Value: "Notary Pre-Assessment"
Name and Value are what I need.
The controller returns a string formatted as JSON, which can then be parsed into a JavaScript object and used as such.
You need to parse the data once and then you'll have an object you can use.
var obj = JSON.parse(results);
$('#modalName').text(obj.name);
$('#modalMessage').text(obj.message);
Here is the solution for deserializing the JSON object
$("button").click(function () {
var col = $('#requestId');
var jobRequestId = col.data("id");
$.ajax({
url: '#Url.Action("JobPollerParameters", "Tools")',
data: { "jobRequestId": jobRequestId},
success: function(results){
$modal = $('#paramsModal');
$modal.modal("show");
console.log(results);
var name = JSON.stringify(results[0].Name);
var value = JSON.stringify(results[0].Value);
$('#modalName').text(name);
$('#modalMessage').text(value);
}
});
});

Angular how to post data with a button using (change) detector?

I am trying to post data to my REST server. When I use a (change) it sends the data to my rest server. When I try to activate the method on my button it doesnt even try to make a POST call. How can I solve this problem? I can't find anything about it.
HTML file:
<div class="container py-5">
<div class="row">
<div class="col-md-12">
<div class="row">
<div class="col-md-6 mx-auto">
<div class="card rounded-0">
<div class="card-header">
<h3 class="mb-0">Organize</h3>
</div>
<div class="form-group">
<label for="codes" class="m-2">Choose a restaurant:</label>
<form #f="ngForm">
<input
type="text"
list="codes"
class="m-2"
(change)="saveCode($event)">
<datalist id="codes">
<option *ngFor="let c of codeList" [value]="c.name">{{c.name}}</option>
</datalist>
</form>
<button
type="submit"
class="btn btn-primary btn-lg float-none m-2"
id="btnAanmaken"
routerLink="/menu"
(change)="saveCode($event)"
>Aanmaken</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
Typescript file:
// Method to post data to backend
public saveCode(e): void {
const name = e.target.value;
const list = this.codeList.filter(x => x.name === name)[0];
this.restaurant.name = list.name;
this.restaurant.address = list.address;
console.log(list.name);
console.log(list.address);
// Additional information to the server content type
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
// Making an array with the values of the restaurant
const data = {
name: list.name,
address: list.address
};
console.log(data);
// POST method
this.http.post('http://localhost:8080/aquadine-jee/resources/restaurant',
JSON.parse(JSON.stringify(data)) , httpOptions)
// wait till it gets posted to the backend
.subscribe( // subscribe to observable http.post
res => {
console.log("response" + " " + res); // log results otherwise log error
},
err => {
console.log('Error occured');
}
);
}
I tried to call the method by:
<button
type="submit"
class="btn btn-primary btn-lg float-none m-2"
id="btnAanmaken"
routerLink="/menu"
(change)="saveCode($event)"
>Aanmaken</button>
and:
<button
type="submit"
class="btn btn-primary btn-lg float-none m-2"
id="btnAanmaken"
routerLink="/menu"
(click)="saveCode($event)"
>Aanmaken</button>
In addition to the answer by #Moslem, change the button type from submit to button
<button type="button" .. > instead of <button type="submit" ...>
Conflict using routerLink routerLink="/menu" and click event.
change routing when back response.
Inject router: Router class and use this.router.navigateByUrl(url: string)
Router
constructor(private router: Router){
}
public saveCode(e): void{
// POST method
this.http.post('http://localhost:8080/aquadine-jee/resources/restaurant',
JSON.parse(JSON.stringify(data)) , httpOptions)
// wait till it gets posted to the backend
.subscribe( // subscribe to observable http.post
res => {
console.log("response" + " " + res); // log results otherwise log error
this.router.navigateByUrl("/menu")
},
err => {
console.log('Error occured');
}
);
}

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'];
?>

ng-click dont work on list-group items button

I was searching for the solution, but can't resolve it.
I have HomeController and in its constructor I make some functions to work with firebase items. The list group displays todos and buttons, which are connected with data state. The code below shows the todo directive. I'm using scope to exchange the data.
ToDo App
Add Task
<!-- Task List Starts Here -->
<ul class="list-group" ng-show="!isLogged">
<li class="list-group-item clearfix message" ng-repeat="message in messages | filter: {mail : email}" ng-class="{disabled: ! message.done }">
<p class="lead">{{message.text}}</p>
<div>
<span class="pull-right">
<button class="btn btn-default btn-xs"><span class="glyphicon glyphicon-pencil"
ng-click="editTask(message)"></span></button>
<button class="btn btn-primary btn-xs" ng-show="! message.done"><span class="glyphicon glyphicon-ok" ng-click="doneTask(message)"></span></button>
<button class="btn btn-primary btn-xs" ng-show="message.done"><span class="glyphicon glyphicon-repeat" ng-click="unDoneTask(message)"></span></button>
<button class="btn btn-danger btn-xs"><span class="glyphicon glyphicon-remove" ng-click="deleteTask(message)"></span></button>
</span>
</div>
</li>
</ul>
<!-- Task List Ends Here -->
</div>
And then I have main.controller file
export default class MainController {
constructor($scope, $firebaseArray, $firebaseAuth) {
var ref = new Firebase("https://learn11.firebaseio.com/todos");
$scope.messages = $firebaseArray(ref);
$scope.addMessage = function() {
$scope.messages.$add({
text: $scope.newMessageText
});
};
$scope.isLogged = false
$scope.loginUser = function() {
ref.authWithPassword({
email: $scope.email,
password: $scope.password
}, function(error, authData) {
if (error) {
$scope.isLogged = false
console.log("Login Failed!", error);
}
else {
$scope.isLogged = true
console.log($scope.isLogged)
}
});
};
$scope.addTask = function() {
var message_ref = new Firebase('https://learn11.firebaseio.com/todos');
var newMessageRef = message_ref.push();
newMessageRef.set({
'done': true,
'text': $scope.task,
'mail': $scope.email
});
};
$scope.editTask = function(message) {
$scope.task = $scope.messages[index].text;
console.log($scope.messages[index].text);
$scope.editIndex = index;
}
$scope.doneTask = function(message) {
$scope.messages[index].done = true;
}
$scope.unDoneTask = function(message) {
$scope.messages[index].done = false;
}
$scope.deleteTask = function(message) {
console.log(message)
$scope.messages.$remove(message)
}
}
}
Can you please help me? What can I do to make it work? And also do you know why isLogged state is not changed in view while it has changed in controller?
Try to use $scope.$apply(function () {$scope.isLogged = true}) for changing isLogged.

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