Jquery ajax passing null values to MVC controller - javascript

The problem:
I am trying to save events in a calendar by passing the content in ajax to my controller function. But I keep on getting null values being passed to my database. I have checked the console.log under Network tools in browsers and all of the data is null except EventId .
I know inserting the events into the database is working but it seems like the data being inserted is not being read by either Ajax or there's something wrong with my controller. Why do I keep on getting null values?
What the data in my database looks like after I saved the events
Here's my controller
[HttpPost]
public IActionResult SaveEvent(Event data)
{
var userId = _userManager.GetUserId(User);
var status = false;
if (string.IsNullOrEmpty(userId))
{
Response.StatusCode = (int)HttpStatusCode.InternalServerError;
return Json(new { Data = false, ErrorMessage = "no User Id!" });
}
if (data.EventId > 0)
{
//Update the event
var v = db.Events.Where(a => a.EventId == data.EventId).FirstOrDefault();
if (v != null)
{
userId = data.UserId;
v.EventId = data.EventId;
v.Title = data.Title;
v.Counselor = data.Counselor;
v.Description = data.Description;
v.EventStart = data.EventStart;
v.EventEnd = data.EventEnd;
v.AllDay = data.AllDay;
v.ThemeColor = data.ThemeColor;
}
}
else
{
db.Events.Add(data);
}
db.SaveChanges();
status = true;
return Json(new { Data = data, status});
}
This is my Event class:
public class Event {
public string UserId { get; set; }
public int? EventId { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string EventStart { get; set; }
public string EventEnd { get; set; }
public string Counselor { get; set; }
public string ThemeColor { get; set; }
public bool AllDay { get; set; }
}
and my Ajax function
function GenerateCalender(events) {
jq341('#calender').fullCalendar('destroy');
jq341('#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) {
selectedEvent = calEvent;
jq341('#myModal #eventTitle').text(calEvent.title);
var description = jq341('<div />');
description.append(jq341('<p />').html('<b>Start:</b>' + calEvent.start.format("DD-MMM-YYYY HH:mm a")));
if (calEvent.end != null) {
description.append(jq341('<p/>').html('<b>End:</b>' + calEvent.end.format("DD-MMM-YYYY HH:mm a")));
}
description.append(jq341('<p />').html('<b>Description:</b>' + calEvent.description));
jq341('#myModal #pDetails').empty().html(description);
jq341('#myModal').modal();
},
selectable: true,
select: function (start, end) {
selectedEvent = {
userID: '',
eventID: 0,
title: '',
counselor: '',
start: start,
end: end,
description: '',
allDay: false,
color: ''
};
openAddEditForm();
jq341('#calendar').fullCalendar('unselect');
},
editable: true,
eventDrop: function (event) {
var data = {
UserId: event.userID,
EventId: event.eventID,
Title: event.title,
Counselor: event.counselor,
EventStart: event.start.format('DD/MM/YYYY HH:mm A'),
EventEnd: event.end != null ? event.end.format('DD/MM/YYYY HH:mm A') : null,
Description: event.description,
AllDay: event.allDay,
ThemeColor: event.color,
};
SaveEvent(data);
}
})
}
function openAddEditForm() {
if (selectedEvent != null) {
jq341('#hdEventID').val(selectedEvent.eventID);
jq341('#hdUserID').val(selectedEvent.userID);
jq341('#txtSubject').val(selectedEvent.title);
jq341('#ddCounselor').val(selectedEvent.counselor);
jq341('#txtStart').val(selectedEvent.start.format('DD/MM/YYYY HH:mm A'));
jq341('#chkIsFullDay').prop("checked", selectedEvent.allDay || false);
jq341('#chkIsFullDay').change();
jq341('#txtEnd').val(selectedEvent.end != null ? selectedEvent.end.format('DD/MM/YYYY HH:mm A') : '');
jq341('#txtDescription').val(selectedEvent.description);
jq341('#ddThemeColor').val(selectedEvent.color);
}
jq341('#myModal').modal('hide');
jq341('#myModalSave').modal();
}
jq341('#btnSave').click(function () {
//Validation
if (jq341('#txtSubject').val().trim() == "") {
alert('Title required');
return;
}
if (jq341('#txtStart').val().trim() == "") {
alert('Start date required');
return;
}
if (jq341('#chkIsFullDay').is(':checked') == false && jq341('#txtEnd').val().trim() == "") {
alert('End date required');
return;
}
else {
var format_start = jq341('#txtStart').val().replace(' ', '-').split('-');
var nowy_start = format_start[1] + '-' + format_start[0] + '-' + format_start[2] + ' ' + format_start[3];
var format_end = jq341('#txtEnd').val().replace(' ', '-').split('-');
var nowy_end = format_end[1] + '-' + format_end[0] + '-' + format_end[2] + ' ' + format_end[3];
}
//edited
var data = {
UserId: jq341('#hdUserID').val(),
EventId: jq341('#hdEventID').val(),
Title: jq341('#txtSubject').val().trim(),
Counselor: jq341('#ddCounselor').val(),
EventStart: jq341('#txtStart').val().trim(),
EventEnd: jq341('#chkIsFullDay').is(':checked') ? null : jq341('#txtEnd').val().trim(),
Description: jq341('#txtDescription').val(),
ThemeColor: jq341('#ddThemeColor').val(),
AllDay: jq341('#chkIsFullDay').is(':checked')
}
alert(data);
SaveEvent(data);
// call function for submit data to the server
})
function SaveEvent(data) {
jq341.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "JSON",
url: '/Calendar/SaveEvent',
data: JSON.stringify(data),
success: function (data) {
console.log(data)
if (data.status) {
//Refresh the calender
FetchEventAndRenderCalendar();
jq341('#myModalSave').modal('hide');
}
},
error: function () {
alert('Failed', ErrorMessage);
}
})
}
my cshtml
<div id="myModalSave" 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">Appointments</h4>
</div>
<div class="modal-body">
<form class="col-md-12 form-horizontal">
<input type="text" id="hdEventID" value="0" />
<input type="hidden" id="hdUserID">
<div class="form-group">
<label>Subject</label>
<input type="text" id="txtSubject" class="form-control" />
</div>
<div class="form-group">
<label>Counselor</label>
<select id="ddCounselor" class="form-control">
<option value="0">Choose your counselor</option>
<option value="DrSalwa">Dr Salwa</option>
<option value="DrNorzaiham">Dr Norzaiham</option>
<option value="Nasri">Sir Nasri</option>
<option value="Adibah">Ms. Adibah</option>
</select>
</div>
<div class="form-group">
<label>Start</label>
<div class="input-group date" id="dtp1">
<input type="text" id="txtStart" class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
<div class="form-group">
<div class="checkbox">
<label><input type="checkbox" id="chkIsFullDay" checked="checked" /> Is Full Day event</label>
</div>
</div>
<div class="form-group" id="divEndDate" style="display:none">
<label>End</label>
<div class="input-group date" id="dtp2">
<input type="text" id="txtEnd" class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
<div class="form-group">
<label>Description</label>
<textarea id="txtDescription" rows="3" class="form-control"></textarea>
</div>
<div class="form-group">
<label>Theme Color</label>
<select id="ddThemeColor" class="form-control">
<option value="">Default</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="black">Black</option>
<option value="green">Green</option>
</select>
</div>
<button type="button" id="btnSave" class="btn btn-success">Save</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</form>
</div>
</div>
</div>
</div>
Below are screenshots of the Network tool
Using [FormBody] but getting that null exception in if(data.eventId >0) in controller
Below is [FormBody] is omitted from the controller but still getting null values except EventId

First, you should add the [FromBody] attribute, otherwise the data will not be successfully obtained.
You can add a breakpoint in your action to observe whether the binding is successful.
Then, modify your db.Add() method, because your data contains EventId, and in your database I see EventId as the primary key, and your primary key is auto-incremented. If you add a New entity of EventId, then an exception will be thrown.
You can try change your action like below:
[HttpPost]
public IActionResult SaveEvent([FromBody]Event data)
{
var userId = _userManager.GetUserId(User);
var status = false;
if (string.IsNullOrEmpty(userId))
{
Response.StatusCode = (int)HttpStatusCode.InternalServerError;
return Json(new { Data = false, ErrorMessage = "no User Id!" });
}
if (data.EventId > 0)
{
//Update the event
var v = db.Events.Where(a => a.EventId == data.EventId).FirstOrDefault();
if (v != null)
{
userId = data.UserId;
v.EventId = data.EventId;
v.Title = data.Title;
v.Counselor = data.Counselor;
v.Description = data.Description;
v.EventStart = data.EventStart;
v.EventEnd = data.EventEnd;
v.AllDay = data.AllDay;
v.ThemeColor = data.ThemeColor;
}
}
else
{
var data1 = new Event
{
UserId=data.UserId,
Title = data.Title,
Counselor = data.Counselor,
Description = data.Description,
EventStart = data.EventStart,
EventEnd = data.EventEnd,
AllDay = data.AllDay,
ThemeColor = data.ThemeColor,
};
db.Events.Add(data1);
}
db.SaveChanges();
status = true;
return Json(new { Data = data, status});
}

Related

Client side validation not working in MVC

The client-side validation in ASP.Net Core is not working. I have the following code:
#model VeoScheduling.Models.SignInModel
#{
ViewData["Title"] = "SignIn";
}
<div class="login">
<h2>Sign In</h2>
<div>
<form method="post" asp-action="SignIn">
<input type="hidden" asp-for="RedirectUrl" />
<div class="form-group">
<label asp-for="Email" class="control-label"></label>
<input type="email"
data-bind="value: email" asp-for="Email"
class="form-control" />
<span asp-validation-for="Email" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Password"
class="control-label"></label>
<input type="password" asp-for="Password"
data-bind="value: password"
class="form-control" />
<span asp-validation-for="Password" class="text-danger"></span>
</div>
<div class="form-group">
<label class="control-label">Account</label>
<select name="accountSelected" style="margin:5px;width:200px"
data-bind='options: availableAccounts, optionsText: "value", optionsValue: "key", value: selectedAccount,event:{change: accountSelected()}'></select>
</div>
<br />
#if (Model.Error != "" || Model.Error != null)
{
<p style="color:red">#Html.Raw(Model.Error)</p>
}
</form>
</div>
</div>
#section Scripts{
<script>
var vModel = #Html.Raw(Json.Serialize(Model))
</script>
<script src="~/js/signIn.js" asp-append-version="true"></script>
}
I have also added javascript validation files and I can see they are being loaded when I run but still client-side validation is not working.
I have applied required attribute for both email and password filed. But client-side validation is still not working.
public class SignInModel
{
[Required(ErrorMessage ="Email is required")]
public string Email { get; set; }
[Required(ErrorMessage ="Password is required")]
public string Password { get; set; }
[DisplayName("Forgot Password")]
public bool ForgotPassword { get; set; }
public string RedirectUrl { get; set; }
public string Error { get; set; }
}
$(document).ready(function () {
self.vm = new viewModel(self.vModel);
ko.applyBindings(self.vm);
});
Below is the js code.
var viewModel = function (model) {
var self = this;
//properties
self.email = ko.observable('');
self.password = ko.observable('');
self.redirectUrl = model.redirectUrl;
self.availableAccounts = ko.observableArray(model.availableAccounts);
self.selectedAccount = ko.observable(null);
//events
self.signOn = function () {
var payloadData = {
'email': self.email(),
'password': self.password(),
'accountSelected': self.selectedAccount()
};
var url = window.location.origin + '/account/SignIn';
CallService("Post", url, payloadData)
.done(function (data) {
var url = window.location.origin + self.redirectUrl;
window.location.replace(url);
});
};
self.accountSelected = function (e, d) {
//alert(self.selectedStack());
};
//methods
self.forgotPassword = ko.observable(false);
self.resetPassword = function () {
$('#loader').show();
var payloadData = {
'email': self.email()
};
var url = window.location.origin + '/API/resetPassword'
$.post(url, payloadData)
.always(function () {
$('#loader').hide();
})
.fail(function (xhr, status, error) {
alert('resetPassword(): error' + xhr.responseText);
})
.done(function (data) {
alert("reset email sent.");
});
};
//ajax
self.getUsersAccounts = function () {
if (self.email() === "")
return;
var payloadData = {
'email': self.email()
};
var url = window.location.origin + '/API/GetAccountsByEmail';
CallService("GET", url, payloadData)
.done(function (data) {
self.availableAccounts.removeAll();
self.availableAccounts(data);
});
};
//computed
self.userChanged = ko.computed(function () {
var userID = self.email();
//alert(userID);
//console.log(userID);
self.getUsersAccounts();
});
self.forgotChecked = ko.computed(function () {
var checked = self.forgotPassword();
var email = self.email();
if (checked) {
if (email === '') {
alert("Please fill in email to reset password");
self.forgotPassword(false);
}
else {
alert("An email link will be sent to your email address.");
self.resetPassword();
self.forgotPassword(false);
}
}
});
//init
if (model.availableAccounts.length === 1) {
self.selectedAccount(model.availableAccounts[0].key);
}
};
$(document).ready(function () {
self.vm = new viewModel(self.vModel);
ko.applyBindings(self.vm);
});
you could try:
<form id="someform">
......
</form>
<script>
.....
if ($("#someform").valid())
{
//ajax codes
}
else {
return false;
}
</script>
also you could try:
var somevalue = document.getElementById("someId").value;
if (somevalue == null || somevalue == '')
{
$('#somespanId').html("*required");
return false;
}

Ajax POST with ASP.NET Razor

I am developing an ASP.NET core Razor application and I have a form that I am posting, but I don't want the page to reload on submit. I read that this can be avoided by using Ajax, but i'm not sure how to implement this.
This is my form:
<form id="bankDropdown" method="post">
<div>
<label class="ratings-text" for="bank">Select Bank:</label>
<select name="BankOptions" class="form-control ratings-text" style="width:21%" id="bank">
#foreach (var bank in Model.BankLists)
{
<option name="BankOptions" value="#bank.ShortName" id="selection">#bank.ShortName</option>
}
</select>
</div>
<br />
<div>
<label>Enter Start Date:</label>
<input type="date" asp-for="DateSelect.DateMonthYear1" class="DateMonthYear" name="DateMonthYear1">
<i data-toggle="tooltip" title="Set to first day of the month for optimal results" class="far fa-question-circle"></i>
</div>
<br />
<div>
<label>Enter End Date:</label>
<input type="date" asp-for="DateSelect.DateMonthYear" class="DateMonthYear" name="DateMonthYear" required>
<i data-toggle="tooltip" title="Set to last or current day of the month for optimal results" class="far fa-question-circle"></i>
</div>
<br />
<div>
<input class="ratings-button" type="submit" value="Submit"/>
</div>
</form>
This is my POST function in my page model:
public IActionResult OnPost(string DateMonthYear, string DateMonthYear1, string BankOptions)
{
CurrentDate = string.Format(DateMonthYear);
SelectBank = BankOptions;
BankLists = ModelService.RunBankList();
TotalBankCollections = ModelService.RunTotalBankCollection1(DateMonthYear);
TotalTransactionCounts = ModelService.RunTotalTransactionCount1(DateMonthYear1, DateMonthYear);
long floatTotalCount = 0;
int intVolumeCount = 0;
string stringTotalVolume = "";
//get individual bank monthly collections
foreach (var collection in TotalBankCollections)
{
if (BankOptions == collection.ShortName)
{
string myBank = collection.TotalCollection;
BankCollection = Convert.ToDecimal(myBank).ToString("#,###,###.##");
}
}
//get total collections from all the banks
foreach (var collection in TotalBankCollections)
{
floatTotalCount += (long)Convert.ToDouble(collection.TotalCollection);
string stringTotalCount = Convert.ToDecimal(floatTotalCount).ToString("#,###,###.##");
TotalCollectionCount = stringTotalCount;
}
//get individual monthly volume collections
foreach (var collection in TotalTransactionCounts)
{
if (BankOptions == collection.ShortName)
{
string myBank = collection.TotalCount;
MonthlyVolumeCount = Convert.ToDecimal(myBank).ToString("#,##0");
}
}
//get total transactions of all banks
foreach (var collection in TotalTransactionCounts)
{
intVolumeCount += int.Parse(collection.TotalCount);
stringTotalVolume = intVolumeCount.ToString("#,##0");
TotalVolumeCount = stringTotalVolume;
}
return Page();
}
This is what I have so far, I have never used Ajax before and I have a project deadline:
$.ajax({
type: "POST",
url: "/Identity/Account/Ratings",
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function (response) {
alert(response);
},
failure: function (response) {
alert(response);
}
});
Thanks for the help.
If you want to use ajax with post method in razor page,here is a demo:
TestFormPost.cshtml(script):
$("#bankDropdown").on('submit', function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "",
data: $("#bankDropdown").serialize(),
headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
success: function (data) {
}
});
})
TestFormPost.cshtml.cs:
public class TestFormPostModel : PageModel
{
[BindProperty]
public List<Bank> BankLists { get; set; }
[BindProperty]
public DateSelect DateSelect { get; set; }
public IActionResult OnGet()
{
BankLists = new List<Bank> {
new Bank{ ShortName="bank1"},
new Bank{ ShortName="bank2"},
new Bank{ ShortName="bank3"}
};
return Page();
}
public IActionResult OnPost(string DateMonthYear, string DateMonthYear1, string BankOptions) {
return Page();
}
}
public class Bank
{
public string ShortName { get; set; }
}
public class DateSelect
{
public string DateMonthYear { get; set; }
public string DateMonthYear1 { get; set; }
}
result:
you can prevent form submission by
$('form').on('submit',function(e){
e.preventDefault();
////then ajax call
})

Why does my code not display data on the calendar

I have a database table of some courses. I am trying to add new course to this db and then display it on calendar but I see alert error3.
function SaveCourse(data) {
$.ajax({
type: "POST",
url: '/home/SaveCourse',
data: data,
success: function (data) {
if (data.any) {
//Refresh the calender
FetchCourseAndRenderCalendar();
$('#myModalSave').modal('hide');
}
},
error: function () {
alert('Failed3');
}
});
}
I have a calendar and I need to add a new course. I click add, a form appears ... I fill it out and I see an error (Failed3)
at the same time, when I debug I see data in the controller (SaveCourse (Course c))
here is my index
#{
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="courseTitle"></span></h4>
</div>
<div class="modal-body">
<button id="btnDelete" class="btn btn-default btn-sm pull-right">
<span class="glyphicon glyphicon-remove"></span> Remove
</button>
<button id="btnEdit" class="btn btn-default btn-sm pull-right" style="margin-right:5px;">
<span class="glyphicon glyphicon-pencil"></span> Edit
</button>
<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>
<div id="myModalSave" 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">Save Course</h4>
</div>
<div class="modal-body">
<form class="col-md-12 form-horizontal">
<input type="hidden" id="hdCourseID" value="0" />
<div class="form-group">
<label>Subject</label>
<input type="text" id="txtSubject" class="form-control" />
</div>
<div class="form-group">
<label>Start</label>
<div class="input-group date" id="dtp1">
<input type="text" id="txtStart" class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
<div class="form-group" id="divEndDate" style="display:none">
<label>End</label>
<div class="input-group date" id="dtp2">
<input type="text" id="txtEnd" class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
<div class="form-group">
<label>Description</label>
<textarea id="txtDescription" rows="3" class="form-control"></textarea>
</div>
<div class="form-group">
<label>Column Color</label>
<select id="ddColumnColor" class="form-control">
<option value="green">Default</option>
<option value="blue">Blue</option>
</select>
</div>
<button type="button" id="btnSave" class="btn btn-success">Save</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</form>
</div>
</div>
</div>
</div>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/css/bootstrap-datetimepicker.min.css" rel="stylesheet" />
<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 courses = [];
var selectedCourse = null;
FetchCourseAndRenderCalendar();
function FetchCourseAndRenderCalendar() {
courses = [];
$.ajax({
type: "GET",
url: "/home/GetCourseJsonResults",
success: function (data) {
$.each(data, function (i, v) {
courses.push({
courseID: v.CourseID,
title: v.Subject,
description: v.Description,
start:v.Start,
end: v.End,
color: v.ColumnColor
});
});
GenerateCalender(courses);
},
error: function () {
alert('failed1');
}
});
}
function GenerateCalender(courses) {
$('#calender').fullCalendar('delete');
$('#calender').fullCalendar({
contentHeight: 400,
defaultDate: new Date(),
timeFormat: 'h(:mm)a',
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay,agenda'
},
courseLimit: true,
courseColor: '#378006',
courses: courses,
courseClick: function (calCourse, jsEvent, view) {
selectedCourse = calCourse;
$('#myModal #courseTitle').text(calCourse.title);
var $description = $('<div/>');
$description.append($('<p/>').html('<b>Start:</b>' + calCourse.start.format("DD-MMM-YYYY HH:mm a")));
if (calCourse.end != null) {
$description.append($('<p/>').html('<b>End:</b>' + calCourse.end.format("DD-MMM-YYYY HH:mm a")));
}
$description.append($('<p/>').html('<b>Description:</b>' + calCourse.description));
$('#myModal #pDetails').empty().html($description);
$('#myModal').modal();
},
selectable: true,
select: function (start, end) {
selectedCourse = {
courseId: 0,
title: '',
description: '',
start: start,
end: end,
color: ''
};
openAddEditForm();
$('#calendar').fullCalendar('unselect');
},
editable: true,
courseDrop: function (course) {
var data = {
CourseID: course.courseId,
Subject: course.title,
Start: course.start.format('DD/MM/YYYY HH:mm A'),
End: course.end != null ? course.end.format('DD/MM/YYYY HH:mm A') : null,
Description: course.description,
ColumnColor: course.color
};
SaveCourse(data);
}
});
}
$('#btnEdit').click(function () {
//Open modal dialog for edit course
openAddEditForm();
});
$('#btnDelete').click(function () {
if (selectedCourse != null && confirm('Are you sure?')) {
$.ajax({
type: "POST",
url: '/home/DeleteCourse',
data: { 'courseId': selectedCourse.courseId },
success: function (data) {
data.status = true;
//Refresh the calender
FetchCourseAndRenderCalendar();
$('#myModal').modal('hide');
},
error: function () {
alert('Failed2');
}
});
}
});
//$('#dtp1,#dtp2').datetimepicker({
// format: 'DD/MM/YYYY HH:mm A'
//});
function openAddEditForm() {
if (selectedCourse != null) {
$('#hdCourseID').val(selectedCourse.courseId);
$('#txtSubject').val(selectedCourse.title);
$('#txtStart').val(selectedCourse.start.format('DD/MM/YYYY HH:mm A'));
$('#txtEnd').val(selectedCourse.end != null ? selectedCourse.end.format('DD/MM/YYYY HH:mm A') : '');
$('#txtDescription').val(selectedCourse.description);
$('#ddColumnColor').val(selectedCourse.color);
}
$('#myModal').modal('hide');
$('#myModalSave').modal();
}
$('#btnSave').click(function () {
//Validation/
if ($('#txtSubject').val().trim() == "") {
alert('Subject required');
return;
}
if ($('#txtStart').val().trim() == "") {
alert('Start date required');
return;
}
else {
var startDate = moment($('#txtStart').val(), "DD/MM/YYYY HH:mm A").toDate();
var endDate = moment($('#txtEnd').val(), "DD/MM/YYYY HH:mm A").toDate();
if (startDate > endDate) {
alert('Invalid end date');
return;
}
}
var data = {
CourseID: $('#hdCourseID').val(),
Subject: $('#txtSubject').val().trim(),
Description: $('#txtDescription').val(),
DateStart: $('#txtStart').val().trim(),
DateEnd: $('#chkIsFullDay').is(':checked') ? null : $('#txtEnd').val().trim(),
ColumnColor: $('#ddColumnColor').val()
};
SaveCourse(data);
// call function for submit data to the server
});
function SaveCourse(data) {
$.ajax({
type: "POST",
url: '/home/SaveCourse',
data: data,
success: function (data) {
if (data.any) {
//Refresh the calender
FetchCourseAndRenderCalendar();
$('#myModalSave').modal('hide');
}
},
error: function () {
alert('Failed3');
}
});
}
})
</script>
}
my controller
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using UberDrive.Data;
using UberDrive.Models;
namespace My.Controllers
{
public class HomeController : Controller
{
private readonly AppDbContext _context;
public HomeController(AppDbContext context)
{
_context = context;
}
public IActionResult Index()
{
return View();
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
//todo
public async Task<JsonResult> GetCourseJsonResults()
{
var res = await _context.Сourses.AsNoTracking().ToListAsync();
return new JsonResult(res);
}
[HttpPost]
public JsonResult SaveCourse(Сourse c)
{
// >0
if (c.СourseId != 0)
{
var course = _context.Сourses.FirstOrDefault(x => x.СourseId == c.СourseId);
// update find course
if (course != null)
{
course.Subject = c.Subject;
course.Description = c.Description;
course.DateStart = c.DateStart;
course.DateEnd = c.DateEnd;
course.ColumnColor = c.ColumnColor;
}
}
else
{
_context.Сourses.Add(c);
}
_context.SaveChanges();
return new JsonResult (_context.Сourses.AsNoTracking().ToListAsync());
}
[HttpPost]
public JsonResult DeleteCourse(int courseId)
{
var c = _context.Сourses.FirstOrDefault(x => x.СourseId == courseId);
if (c != null)
{
_context.Сourses.Remove(c);
_context.SaveChanges();
}
return new JsonResult(_context.Сourses.AsNoTracking().ToListAsync());
}
}
}
and Сourse class
public class Сourse
{
public int СourseId { get; set; }
[Required, StringLength(120)]
public string Subject { get; set; }
public string Description { get; set; }
public DateTime DateStart { get; set; }
public DateTime DateEnd { get; set; }
[Required, StringLength(20)]
public string ColumnColor { get; set; }
}
tell me what is the problem
Wild guess, but not supplying content type or using [FromBody] might be it.
function SaveCourse(data) {
$.ajax({
type: "POST",
url: '/home/SaveCourse',
contentType: "application/json",
data: data,
success: function (data) {
if (data.any) {
//Refresh the calender
}
},
error: function () {
alert('Failed3');
}
});
}
And decorate your controller action with [FromBody] =>
[HttpPost]
public JsonResult SaveCourse([FromBody]Сourse c)
{
// Code ommitted
}

500 Internal Server Error on JSON Post ASP.net MVC

When I try to send a variable to JSON on ASP.net MVC, I am getting error like below:
jquery-2.2.3.min.js:4 GET http://localhost:58525/Order/GetAddress/?userid=42&email=asandtsale%40gmail.com 500 (Internal Server Error)
My controller:
public JsonResult GetAddress(int uservalue, string email)
{
UserService rpuser = new UserService();
DATA.Models.ORM.Entity.UserEntity.User userentity = rpuser.FirstOrDefault(x => x.Id == uservalue);
Models.DTO.OrderDTO.NewAddressVM addressmodel = new Models.DTO.OrderDTO.NewAddressVM();
addressmodel.FirstName = userentity.Name;
return Json(addressmodel.FirstName, JsonRequestBehavior.AllowGet);
}
View:
<script>
$(document).ready(function () {
$("#okbutton").click(function () {
var e = document.getElementById("emailadd");
var uservalue = e.options[e.selectedIndex].value;
var usertext = e.options[e.selectedIndex].text;
var link = "/Order/GetAddress/";
$.ajax({
type: "GET",
url: link,
data: {userid: uservalue, email: usertext},
success: function (result) {
if (result == "accept") {
$("div#voucher-result").html('<span style="color:green; font-weight:bold;">Your voucher code is valid. Discount price: <text style="font-size:19px;">£50</text><br />If you complete your order you will get a discount of £50.</span>');
} else {
$("div#voucher-result").html('<span style="color:green; font-weight:bold;">Your voucher code is valid. Discount price: <text style="font-size:19px;">£50</text><br />Else</span>');
}
}
});
});
});
And Form:
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Customer</label>
#Html.DropDownListFor(x => x.CustomerId, new SelectList(Model.CustomerList, "Id", "UserName"), new { #class = "form-control select2", #id="emailadd", #placeholder = "" })
</div>
</div>
<div class="col-md-6">
<label></label>
<button type="button" class="btn btn-block btn-success" id="okbutton" style="width:60px;">OK</button>
</div>
<div id="voucher-result"></div>
</div>
GetAddress(int uservalue, string email) expects a parameter called uservalue but in your javascript you are sending over an userid: data: {userid: uservalue, email: usertext}
You should change the parameter uservalue to userid in your controller or change userid to uservalue in your javascript.

String values not being picked up by array in AngularJS

I am currently working on an accounting project and I am experiencing a stupid problem.
I enter the values in text boxes and I click on Add Person button, the values get added but when I click Save to Database button the multiple added values get pushed into database. I am able to insert multiple values in the database but unable to call the multiple entries from the SQL server back again onto my UI.
I have multiple same first names in my table of SQL server and I want to pick up all the values which have the same first name and populate them in $scope.arr I defined in angular code.
When I pass an integer value in my $scope.GetPerson() method, I get the desired result and my array ($scope.arr) gets populated with all the values having the same CustomerCode but when I pass a string value i.e, FirstName in GetPerson method, my array($scope.arr) doesn't get populated with the same First Name values that were placed into the database.
I want the experts to look into this problems and guide me where am I actually doing the mistake.`
My Model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace TestProj.Models
{
public class TestModel
{
public int ID { get; set; }
public int CustomerCode { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public decimal Debit { get; set; }
public decimal Credit { get; set; }
}
}
My Angular JS script:
var app = angular.module("TestApp", []);
app.controller("TestCtrl", function ($scope, TestService) {
$scope.arr = [];
GetAllPers();
function GetAllPers() {
var getPersData = TestService.getPersons();
getPersData.then(function (Persons) {
$scope.persons = Persons.data;
}, function () {
alert('Error in getting Person records');
});
}
$scope.addPerson = function () {
var obj = {
CustomerCode: $scope.customercode,
FirstName: $scope.firstname,
LastName: $scope.lastname,
Debit: $scope.debit,
Credit: $scope.credit,
};
$scope.arr.push(obj);
};
$scope.savePerson = function () {
var TestData = TestService.AddPer($scope.arr);
TestData.then(function (msg) {
$scope.customercode = "";
$scope.firstname = "";
$scope.lastname = "";
$scope.debit = "";
$scope.credit = "";
GetAllPers();
alert(msg.data);
for (var i = 0; i < $scope.arr.length; i++) {
$scope.arr.pop();
}
}, function () {
alert('Error In Adding Person');
});
};
$scope.GetPerson = function (test) {
var getTestData = TestService.getPers(test.FirstName);
getTestData.then(function (_test) {
$scope.arr = _test.data;
}, function () {
alert('Error in getting person records');
});
}
});
app.service("TestService", function ($http) {
this.getPersons = function () {
return $http.get("/Test/GetAllPers");
}
this.AddPer = function (person) {
var response = $http({
method: "post",
url: "/Test/AddPerson",
data: JSON.stringify(person),
dataType: "json",
});
console.log(response);
return response;
}
this.getPers = function (persname) {
var response = $http({
method: "post",
url: "/Test/GetPersonByFName",
params: {
firstname: JSON.stringify(persname)
}
});
return response;
}
});
My C# controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TestProj.Models;
namespace TestProj.Controllers
{
public class TestController : Controller
{
TestContext dc = new TestContext();
// GET: Test
public ActionResult Index()
{
return View();
}
public JsonResult GetAllPers()
{
var personList = dc.TestModels.ToList();
return Json(personList, JsonRequestBehavior.AllowGet);
}
public JsonResult GetPersonByFName(string firstname)
{
var q = (from ab in dc.TestModels.Where(b => b.FirstName == firstname) select ab);
return Json(q, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public string AddPerson(List<TestModel> test)
{
bool val = false;
foreach (var t in test)
{
if (t != null)
{
dc.TestModels.Add(t);
val = true;
}
else
{
val = false;
}
}
dc.SaveChanges(); //save context at the end, when no error occurs
if (val == true)
{
return "Success";
}
else
{
return "Failed";
}
}
}
}
My HTML:
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<div ng-controller="TestCtrl">
<form>
<button class="btn" data-toggle="modal" data-target="#myModal">Show records</button><br />
Customer Code: <input class="form-control" ng-model="customercode" /><br />
FirstName: <input class="form-control" ng-model="firstname" /><br />
LastName: <input class="form-control" ng-model="lastname" /><br />
Debit: <input class="form-control" ng-model="debit" /><br />
Credit: <input class="form-control" ng-model="credit" /><br />
<button class="btn btn-success" ng-click="addPerson()">Add Person</button>
<button class="btn btn-success" ng-click="savePerson()">Save To DB</button>
#*Table for showing pushed values*#
<table class="table table-bordered">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Debit</th>
<th>Credit</th>
</tr>
<tr ng-repeat="a in arr">
<td>{{a.CustomerCode}}</td>
<td>{{a.FirstName}}</td>
<td>{{a.LastName}}</td>
<td>{{a.Debit}}</td>
<td>{{a.Credit}}</td>
</tr>
</table>
#*Modal popup*#
<div class="modal fade" role="dialog" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4>Persons</h4>
</div>
<div class="modal-body">
<label class="control-label col-md-2" style="width: auto">Search:</label>
<div class="col-md-8">
<input class="form-control" ng-model="searchfor" />
</div><br />
<table class="table table-hover">
<tr>
<td><b>First Name</b></td>
<td><b>Last Name</b></td>
<td><b>Debit</b></td>
<td><b>Credit</b></td>
<td><b>Select</b></td>
</tr>
<tr ng-repeat="b in persons | filter:searchfor ">
<td>{{b.CustomerCode}}</td>
<td>{{b.FirstName}}</td>
<td>{{b.LastName}}</td>
<td>{{b.Debit}}</td>
<td>{{b.Credit}}</td>
<td>
<button type="button" class="btn btn-success" ng-click="GetPerson(b)" data-dismiss="modal">Select</button>
</td>
</tr>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success" data-toggle="modal" data-target="#myModal">Okay</button>
</div>
</div>
</div>
</div><br />
</form>
</div>
<script src="~/Scripts/MyAngular/Module.js"></script>
The issue is with your getPers(). Adding JSON.stringfy() adds " to your string.
It should be used like this :
this.getPers = function (persname) {
var response = $http({
method: "post",
url: "/Test/GetPersonByFName",
params: {
firstname: persname
}
});
return response;
}

Categories

Resources