我已经为学生建立了在线考试系统,但是我无法通过json传递答案。我收到500个内部错误,我不知道如何解决。
我试图删除长度为json的数据,但是这并没有帮助我无法理解问题所在。一切都传递给控制器,直到db.name.add(item);都起作用。然后返回500内部错误
<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>
控制器:
[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.");
}
它不保存。正如我所说的那样,这是
_context.BoxesStudentobservationforms.Add(item);
await _context.SaveChangesAsync();
然后返回500 intenval error
。它正在工作,但突然停止在本地和服务器上工作。
输出:
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; }
}
答案 0 :(得分:0)
您的500页上显示您的MySql DB上存在与外键(formid <-> formobservationid)相关的错误。
可能的问题:您正在尝试错误的外键或与DB用户权限有关的问题,等等...
我建议您创建一个临时页面,该页面写到屏幕上会抛出此500页错误的确切SQL命令。
然后,复制该SQL并尝试在您的MySql DB上执行(通过heidiSQL或mysqladmin)。
并检查结果。如果再次引发错误,请尝试在数据库端解决。
请通过更新您的问题与我们分享结果。
也请检查此问题: