Search code examples
c#asp.net-mvcfarsi

I get status code 500 while there is no error in my code when I try running in debug mode


When I am trying to run this code in .NET framework, I get a status code 500, but I don't know why...

This is the back end:

public ActionResult getvisit(int id)
{
    var query = __db.Visits
                    .Where(v => v.fkDoctor == id && v.fkPatient == null)
                    .Select(v => new {v.Id, v.sDate})
                    .ToList();

    List<object> visits = new List<object>();

    foreach (var item in query)
    {
        var sdatetime = new PersianDateTime(item.sDate);
// Replacing this new object with a class fixed the issue but i dont' know why?
        visits.Add(new {item.Id, sdatetime.Date, sdatetime.TimeOfDay});
    }

    var result = Json(visits, JsonRequestBehavior.AllowGet);

    return result;
}

Front end:

docSpan.on("change", function () {
        const id = docSpan.val();
        visitSpan.empty();
        visitSpan.append(
            "<option value=''>انتخاب کنید</option>"
        )
        $.post("/Home/getvisit", { id: id })
            .done(function (res) {
                console.log(res);
                for (let item of res) {
                    console.log(item);
                    visitSpan.append(
                        `<option value=${item.id}>${item.sdate} || ${item.stime}</option>`
                    );
                }
            })
            .fail(function () {

            })
            .always(function () {

            });
    })

I don't have any idea why this happens. edit: it got fixed when I replace the unknown object with a class


Solution

  • 500 Internal Server Error you encountered is likely due to ASP.NET MVC's JSON serializer having difficulty serializing the anonymous type new { ... } returned from your action method. By replacing the anonymous type with a named class (VisitViewModel), you provide clarity and structure to the JSON serializer, thus resolving the issue. And always prefer using named classes (ViewModels) for data that needs to be serialized and sent to the client side in ASP.NET MVC applications to avoid such serialization issues.