0

I have build online test system for students but I cannot pass answers with json. I am getting 500 internal error and I couldn't figure it out how to fix.

I tried to remove data which is long json but it did not help I cannot understand what is the problem. everything passes to controller and it works until db.name.add(item); then it returns 500 internal error

<script>
    $("#save_value").click(function(event){
        event.preventDefault();
        jsonObj = [];
        $("input:radio:checked").each(function() {

            var question_id = $(this).attr("data-value");
            var selection = $(this).val();

            item = {}
            item ["selection"] = selection;
            item ["question_id"] = question_id;

            jsonObj.push(item);
        });
        jsonString = JSON.stringify(jsonObj);
        var form = $('#FormId').val();
        var stu = $('#StudentId').val();
        var note = $('#notes').val();

        $.ajax({
            type: 'POST',
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            url: '@Url.Action("SaveForm", "Home")',
            data:  JSON.stringify({'FormId': form , 'StudentId' : stu , 'notes' : note , 'data' : jsonString }),
            success: function(result) {
                console.log('Data received: ');
                console.log(result);
            },
        });
    })
</script>

Controller :

[HttpPost("SaveForm")]
public async Task<IActionResult> SaveForm([FromBody]FromAnswerModel model)
{
    if (model != null)
    {
        var id = int.Parse(User.Identity.Name);
        var member = _context.ClassesStudent.FirstOrDefault(m => m.Id == id);

        int years = 0;
        int months = 0;
        int days = 0;

        DateTime temp = member.BirthDate.Value;

        while (temp.AddYears(1) <= DateTime.Now)
        {
            temp = temp.AddYears(1);
            years++;
        }

        // get months
        while (temp.AddMonths(1) <= DateTime.Now)
        {
            temp = temp.AddMonths(1);
            months++;
        }

        // get days
        while (temp.AddDays(1) <= DateTime.Now)
        {
            temp = temp.AddDays(1);
            days++;
        }

        short positive = 0;
        short negative = 0;

        JArray a = JArray.Parse(model.data);

        foreach (JObject o in a.Children<JObject>())
        {
            foreach (JProperty p in o.Properties())
            {
                string name = p.Name;
                string value = (string)p.Value;
                Console.WriteLine(name + " -- " + value);
                if (value == "A")
                {
                    positive++;
                }
                else if(value =="B")
                {
                    negative++;
                }
            }
        }

        if(negative == 0)
        {
            int sum;

            if(years == 1)
            {
                years = 12;
                sum = years + months;
            }
            else
            {
                years = 12;
                int newMonths = 12 * years;
                sum = months + newMonths;
            }

            var item = new BoxesStudentobservationforms
            {
                Data = model.data,
                SavedDate = DateTime.UtcNow,
                IsCompleted = 1,
                FormId = model.FormId,
                StudentId = model.StudentId,
                Notes = model.notes,
                PositivePoints = positive,
                ImmortalPoints = negative,
                MonthlyWhenSave = (short)sum,
                Result = "Do not support."
            };

            _context.BoxesStudentobservationforms.Add(item);
            await _context.SaveChangesAsync();
        }
        else
        {
            int sum;

            if (years == 1)
            {
                years = 12;
                sum = years + months;
            }
            else
            {
                years = 12;
                int newMonths = 12 * years;
                sum = months + newMonths;
            }

            var item = new BoxesStudentobservationforms
            {
                Data = model.data,
                SavedDate = DateTime.UtcNow,
                IsCompleted = 1,
                FormId = model.FormId,
                StudentId = model.StudentId,
                Notes = model.notes,
                PositivePoints = positive,
                ImmortalPoints = negative,
                MonthlyWhenSave = (short)sum,
                Result = "support"
            };

            _context.BoxesStudentobservationforms.Add(item);
            await _context.SaveChangesAsync();
        }

        return Json("Success");
    }
    return Json("Success.");
}

It does not save. As I said it reaches this part

_context.BoxesStudentobservationforms.Add(item);
await _context.SaveChangesAsync();

Then returns 500 intenval error. It was working but suddenly stopped working on local and server.

output :

Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/1.1 POST https://localhost:5001/SaveForm application/json; charset=UTF-8 733
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Route matched with {action = "SaveForm", controller = "Home"}. Executing controller action with signature System.Threading.Tasks.Task`1[Microsoft.AspNetCore.Mvc.IActionResult] SaveForm(BuyukAile.ViewModels.FromAnswerModel) on controller BuyukAile.Controllers.HomeController (BuyukAile).
Microsoft.AspNetCore.Authorization.DefaultAuthorizationService:Information: Authorization was successful.
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executing action method BuyukAile.Controllers.HomeController.SaveForm (BuyukAile) - Validation state: Valid
Exception thrown: 'Microsoft.EntityFrameworkCore.DbUpdateException' in System.Private.CoreLib.dll
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executed action BuyukAile.Controllers.HomeController.SaveForm (BuyukAile) in 118.6163ms
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware:Error: An unhandled exception has occurred while executing the request.

Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> MySql.Data.MySqlClient.MySqlException: Cannot add or update a child row: a foreign key constraint fails (`buyukaile`.`boxes_studentobservationforms`, CONSTRAINT `boxes_studentobserva_form_id_3b194fa5_fk_boxes_obs` FOREIGN KEY (`form_id`) REFERENCES `boxes_observationform` (`id`))
   at MySql.Data.MySqlClient.MySqlStream.ReadPacket()
   at MySql.Data.MySqlClient.NativeDriver.GetResult(Int32& affectedRow, Int64& insertedId)
   at MySql.Data.MySqlClient.Driver.NextResult(Int32 statementId, Boolean force)
   at MySql.Data.MySqlClient.MySqlDataReader.NextResult()
   at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
   at System.Data.Common.DbCommand.ExecuteDbDataReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken)
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteAsync(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary`2 parameterValues, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
   --- End of inner exception stack trace ---
   at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(DbContext _, ValueTuple`2 parameters, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(IReadOnlyList`1 entriesToSave, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
   at BuyukAile.Controllers.HomeController.SaveForm(FromAnswerModel model) in C:\Users\jacka\OneDrive\Desktop\BA EĞİTİM\BuyukAile\Controllers\HomeController.cs:line 391
   at Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at System.Threading.Tasks.ValueTask`1.get_Result()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeActionMethodAsync()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeNextActionFilterAsync()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
   at Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 133.8998ms 500 text/html; charset=utf-8
 public partial class BoxesStudentobservationforms
    {
        public int Id { get; set; }
        public short MonthlyWhenSave { get; set; }
        public string Notes { get; set; }
        public DateTime? SavedDate { get; set; }
        public short PositivePoints { get; set; }
        public short ImmortalPoints { get; set; }
        public string Result { get; set; }
        public byte IsCompleted { get; set; }
        public string Data { get; set; }
        public int FormId { get; set; }
        public int? StudentId { get; set; }

        public BoxesObservationform Form { get; set; }
        public ClassesStudent Student { get; set; }
    }

Jack
  • 29
  • 1
  • 8
  • "Interval" or "Inter*n*al" error? – Luca Kiebel Aug 04 '19 at 12:51
  • 1
    jquery.min.js:2 POST https://localhost:5001/SaveForm 500 (Internal Server Error) – Jack Aug 04 '19 at 12:52
  • my bad typo @LucaKiebel – Jack Aug 04 '19 at 12:53
  • A 500 error is an error in your **server** code. – Pointy Aug 04 '19 at 12:55
  • @Pointy I also shared controller code but I dont know what is wrong but it keeps going until save changes – Jack Aug 04 '19 at 12:56
  • Do you get any output in your console window? Sometimes a disconnected entity carries errors and ef cannot add it properly, and its output shows up in the console window and not as a response. – RKrogh Aug 04 '19 at 13:00
  • Are you sure `var id = int.Parse(User.Identity.Name);` that name is an `int`? maybe do `TryParse` to make sure and if not return an error? – akaBase Aug 04 '19 at 13:02
  • @RKrogh shared output – Jack Aug 04 '19 at 13:03
  • @akaBase yea it is custom authorization and automatically it gave me name and email by dotnet core so I didnt bother to change – Jack Aug 04 '19 at 13:04
  • Can you attach your context class and if you habe anything added to the ModelBuilder? Maybe the entity is expected to look different and thus cannot be added? – RKrogh Aug 04 '19 at 13:05
  • @RKrogh added it might be about foreign Id which is form id and student id I dont know – Jack Aug 04 '19 at 13:09

1 Answers1

0

Your 500 page says that there is an error on your MySql DB which related the foreign keys (formid <-> formobservationid).

possible problems : you're trying to wrong foreign key or DB user-permission related issues, etc...

I suggest you to create a temporary page which writes to screen exact SQL command that throws this 500 page error.

And then, copy that SQL and try to execute at your MySql DB (via heidiSQL or mysqladmin).

And check the result. If it throws error again, try to solve at Database side.

And please share with us the result by updating your question.

Also please check this SO questions :

Related Question 1

Related Question 2

Cem
  • 48
  • 5