locked
HTTP 500: Server error when posting data to the server RRS feed

  • Question

  • User1984354752 posted

    Dear all

     I'm implementing   CRUD operations via EF using a Generic Repository.   The controller action for loading the data into the jqgrid   namely loco works  fine which means that the Generic Repository structure is well implemented  . However  the action for edit is throwing an HTTP500: Server Error . The  Development Tools debugger reports :  HTTP500: Server Error - The server encountered an unexpected condition that prevent it from fulfilling the request POST -https://localhost: 44346/BeneficaryList/Edit .

    My interpretation is that the  error points to the Edit action in the BeneficiaryList Controller . I highlighted it in yellow and also attached the razor view so you can check what I'm doing wrong . As I previously said the Generic Repository is retrieving  data but is throwing an exception when I post the data to the database.

    GENERIC REPOSITORY CLASS

    public class GenericRepository<TEntity> where TEntity : class

       {

           internal HousingContext context;

           internal DbSet<TEntity> dbSet;

           public GenericRepository(HousingContext context)

           {

               this.context = context;

               this.dbSet = context.Set<TEntity>();

           }

               public virtual IEnumerable<TEntity> Get(

               Expression<Func<TEntity, bool>> filter = null,

               Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,

               string includeProperties = "")

           {

               IQueryable<TEntity> query = dbSet;

     

               if (filter != null)

               {

                   query = query.Where(filter);

               }

               foreach (var includeProperty in includeProperties.Split

                   (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))

               {

                   query = query.Include(includeProperty);

               } 

               if (orderBy != null)

               {

                   return orderBy(query).ToList();

               }

               else

               {

                   return query.ToList();

               }

           }

           public virtual IEnumerable<TEntity> Getallthelist()

    {

               return dbSet.ToList();

           }

           public virtual TEntity GetByID(object id)

           {

               return dbSet.Find(id);

           }

     

           public virtual void Insert(TEntity entity)

           {

               dbSet.Add(entity);

           }

     

           public virtual void Delete(object id)

           {

               TEntity entityToDelete = dbSet.Find(id);

               Delete(entityToDelete);

           }

     

           public virtual void Delete(TEntity entityToDelete)

           {

               if (context.Entry(entityToDelete).State == EntityState.Detached)

               {

                   dbSet.Attach(entityToDelete);

               }

               dbSet.Remove(entityToDelete);

           }

     

           public virtual void Update(TEntity entityToUpdate)

           {

               dbSet.Attach(entityToUpdate);

               context.Entry(entityToUpdate).State = EntityState.Modified;

           }

       }

    }

    ALL REPOSITORIES CLASS

    public class Allrepositories : IDisposable

       {

           private HousingContext context = new HousingContext();

          

           private GenericRepository<Plots_allocated_to_beneficiaries> beneficarieslistsRepository;

           private GenericRepository<Plot> Plotrepository;

     

           public GenericRepository<Plots_allocated_to_beneficiaries>BeneficiarylistRepository

           {

               get

               {

     

                   if (this.beneficarieslistsRepository == null)

                   {

                       this.beneficarieslistsRepository = new GenericRepository<Plots_allocated_to_beneficiaries>(context);

                   }

                   return beneficarieslistsRepository;

               }

           }

     

           public GenericRepository<Plot> PlotlistRepository

           {

               get

               {

     

                   if (this.Plotrepository == null)

                   {

                       this.Plotrepository = new GenericRepository<Plot> (context);

                   }

                   return Plotrepository;

               }

           }

     

           public void Save()

           {

               context.SaveChanges();

           }

     

           private bool disposed = false;

     

           protected virtual void Dispose(bool disposing)

           {

               if (!this.disposed)

               {

                   if (disposing)

                   {

                       context.Dispose();

                   }

               }

               this.disposed = true;

           }

     

           public void Dispose()

           {

               Dispose(true);

               GC.SuppressFinalize(this);

           }

       }

    }

    BENEFICARY CONTROLLER

      

    publicclassBeneficiaryListController : Controller

       {

           private Allrepositories db = new Allrepositories();

     

           // GET: BeneficiaryList

           public ActionResult Index()

           {

               return View();

           }      

           [HttpGet]

           public JsonResult Loco(string sidx, string sort, int page, int rows) => This method loads the data into the JQGRID …..it works fine !!!!!

           {

               sort = (sort == null) ? "" : sort;

               int pageIndex = Convert.ToInt32(page) - 1;

               int pageSize = rows;

     

     

               var listofbeneficiaries = from i in db.BeneficiarylistRepository.Getallthelist().Where(i => i.IdNumber != null).ToList()

                                         select new

                                         {

                                             ID = i.ID,

                                             Fullnames = i.Fullnames,

                                             Idnumber = i.IdNumber,

                                             Surname = i.Surname

                                         };

               int totalRecords = listofbeneficiaries.Count();

               var totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);

               if (sort.ToUpper() == "DESC")

               {

                   listofbeneficiaries = listofbeneficiaries.OrderByDescending(t => t.Idnumber);

                   listofbeneficiaries = listofbeneficiaries.Skip(pageIndex * pageSize).Take(pageSize);

               }

               else

               {

                   listofbeneficiaries = listofbeneficiaries.OrderBy(t => t.Idnumber);

                   listofbeneficiaries = listofbeneficiaries.Skip(pageIndex * pageSize).Take(pageSize);

               }

               var Jsondata = new

               {

                   total = totalPages,

                   page,

                   records = totalRecords,

                   rows = listofbeneficiaries };

     

               return Json(Jsondata, JsonRequestBehavior.AllowGet);

     

           }

        

           [HttpPost]

           public string Edit(Plots_allocated_to_beneficiaries Model)     ======> This is the method that causes the error

           {

              

               string msg;

     

               try

               {

                   if ( ModelState.IsValid)

                   {

                       db.BeneficiarylistRepository.Update(Model);

                      

                       db.Save();

                       msg = "Saved Successfully";

                   }

     

                   else

                   {

                       msg = "Validation data not successfully";

                   }

               }

     

               catch (Exception ex)

     

               {

                   msg = "Error occured:" + ex.Message;

               }

           

               return msg;

           }

     

    RAZOR VIEW.

     

    @{

       Layout = "~/Views/Shared/_Layout.cshtml";

    }

     

     

     

    @section scripts{

       <link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />

       <link href="~/Content/jquery.jqGrid/ui.jqgrid.css" rel="stylesheet" />

     

       <script src="~/Scripts/jquery-3.0.0.min.js"></script>

       <script src="~/Scripts/i18n/grid.locale-en.js"></script>

       <script src="~/Scripts/jquery.jqGrid.min.js"></script>

       }

     

     

    <table id="jgrid"></table>

    <div id="jgrid_page"></div>

     

    <script type='text/javascript'>

     

       $(document).ready(function () {

           $("#jgrid").jqGrid

               ({

                   url: '/BeneficiaryList/Loco',

                   datatype: 'json',

                   mtype: 'GET',

                   colNames: [

                       'ID',

                       'Fullnames',

                       'Idnumber',

                       'Surname'],

                   colModel: [

                       { name: 'ID', index: 'ID', editable: false, key: true },

                       { name: 'Fullnames', index: 'Fullnames', editable: true, key: false, search: true, editrules: { required: true } },

                       { name: 'Idnumber', index: 'Idnumber', editable: true, key: false, search: true, editrules: { required: true, number: true } },

                       { name: 'Surname', index: 'Surname', editable: true, key: false ,search: true ,editrules: { required: true }}],

                  

                   pager: jQuery('#jgrid_page'),

                   rowNum: 20,

                   rowList: [20, 30, 40, 50],

                   height: '100%',

                   viewrecords: true,

                   caption: 'Beneficiary List',

                   emptyrecords: 'No records',

                   jsonReader:

                   {

                       root: "rows",

                       page: "page",

                       total: "total",

                       records: "records",

                       repeatitems: false,

                       Id: "0"

                   },

                  autowidth: true,

                   multiselect: false

               }).navGrid('#jgrid_page', { edit: true, add: true, del: true, search: true, refresh: true },

               {

                       zIndex: 100,

                       url: '/BeneficiaryList/Edit',

                       closeOnEscape: true,

                       closeAfterEdit: true,

                       recreateForm: true,

                       afterComplete: function (response) {

                           if (response.responseText) {

                              alert(response.responseText);

                           }

                       }

               });

     

       });

     

    </script>

    Thanking you in advance.

    Tuesday, January 21, 2020 12:58 PM

Answers

  • User753101303 posted

    Hi,

    You should check the doc for this product. You likely have pass parameters or it could take by default form fields found on the current line ???

    Anyway take the time to start from the actual error. You can then look at the relevant place for this exact error... If you look at code and wonder what happens it takes more time to find multiple possible problems and you still don't know which one happens...

    If you see a 500 error page I expect the exception message to be written to the Windows log by default. You'll see for example if this is a NullReferenceException or whatever and you'll be sure where it happens.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, January 21, 2020 3:12 PM
  • User1535942433 posted

    Hi 9peculiar,

    Accroding to your codes,I create a little test and I could get the value of  Model.So I guess your problem is in the script.

    Could you tell us the error  occur before or after entering this line?

    More details,you could refer to below article:

    https://www.c-sharpcorner.com/article/performing-crud-operation-using-jqgrid-in-Asp-Net-mvc/

    Best regards,

    Yijing Sun

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, January 22, 2020 6:44 AM

All replies

  • User753101303 posted

    Hi

    It's weird as you have basically a try/catch that should return the exception on the client side (which is IMO  a bad idea, exceptions should be reported for analysis to those in charge of keeping the site up and running).

    By defaul it should be written to the Windows event log. It should be much easier to start from the actual exception rather than reading the code and wondering about everything that could make the code to fail...

    edit: also you have a {:} button that allows to make code more legible...

    Tuesday, January 21, 2020 1:17 PM
  • User1984354752 posted

    Hi Patrice:

    Thanks for your feedback and advice. I don't know what I'm doing wrong....if I understood you correctly, I have to go to the windows event log ? . I want if it's not to much to ask that you take a look at another query I posted just now.   It's  a doubt I have …….I pasted the post below for your ease of reference.

    Thanking you in advance.

    Hi there:

    I intend to use ADO.NET via stored procedure to CRUD my Jqgrid in ASP.NET MVC.  I know how fill jqgrid with a stored procedure but don't know how to do implement the Edit, Delete and Insert operations.   

    I'm  going straight to the point as I know how to write my  T-SQL and implement the actions in the controller. I highlighted in yellow where I'm not sure ( I haven't try yet) so you can go straight to yellow line.  

    ADO.NET STORED PROCEDURE PULL FROM DATABASE.

           public int Update(Employee emp)

           {

               int i;

               using (SqlConnection con = new SqlConnection(cs))

                {

                   con.Open();

                   SqlCommand com = new SqlCommand("InsertUpdateEmployee", con);

                   com.CommandType = CommandType.StoredProcedure;

                   com.Parameters.AddWithValue("@Id", emp.EmployeeID);

                  com.Parameters.AddWithValue("@Name", emp.Name);

                   com.Parameters.AddWithValue("@Age", emp.Age);

                   com.Parameters.AddWithValue("@State", emp.State);

                   com.Parameters.AddWithValue("@Country", emp.Country); 

                   i = com.ExecuteNonQuery();

               }

               return i;

           }

     

    STOREDPROCEDURE CONTROLLER:

    public JsonResult Update(Employee emp)

           {

               return Json(empDB.Update(emp), JsonRequestBehavior.AllowGet);

           }

    RAZOR VIEW:

    @{

       Layout = "~/Views/Shared/_Layout.cshtml";

    }

     

     

     

    @section scripts{

       <link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />

       <link href="~/Content/jquery.jqGrid/ui.jqgrid.css" rel="stylesheet" />

     

       <script src="~/Scripts/jquery-3.0.0.min.js"></script>

       <script src="~/Scripts/i18n/grid.locale-en.js"></script>

       <script src="~/Scripts/jquery.jqGrid.min.js"></script>

       }

     

     

    <table id="jgrid"></table>

    <div id="jgrid_page"></div>

     

    <script type='text/javascript'>

     

       $(document).ready(function () {

           $("#jgrid").jqGrid

               ({

                   url: '/xxxxxxxx/xxxxxxx',

                   datatype: 'json',

                   mtype: 'GET',

                   colNames: [

                       'ID',

                       'Name',

                       'Age',

                       'State',

                    'Country'],

                   colModel: [

                       { name: 'ID', index: 'ID', editable: false, key: true },

                       { name: 'Fullnames', index: 'Fullnames', editable: true, key: false, search: true, editrules: { required: true } },

                       { name: 'Age', index: 'Age', editable: true, key: false, search: true, editrules: { required: true, number: true } },

                       { name: 'State', index: 'State', editable: true, key: false ,search: true ,editrules: { required: true }},

                      { name: 'Country', index: 'Country', editable: true, key: false ,search: true ,editrules: { required: true }}],

                  

                   pager: jQuery('#jgrid_page'),

                   rowNum: 20,

                   rowList: [20, 30, 40, 50],

                   height: '100%',

                   viewrecords: true,

                   caption: 'Beneficiary List',

                   emptyrecords: 'No records',

                   jsonReader:

                   {

                       root: "rows",

                      page: "page",

                       total: "total",

                       records: "records",

                       repeatitems: false,

                       Id: "0"

                   },

                   autowidth: true,

                   multiselect: false

               }).navGrid('#jgrid_page', { edit: true, add: true, del: true, search: true, refresh: true },

               {

                       zIndex: 100,

                       url: '/storedprocedure/Update', =>Is this right ??? I mean do I have to pass the parameters by creating a script function or the  above controller  deals with the JSON data ??????   If not ….can you please elaborate how to do it ???

                       closeOnEscape: true,

                       closeAfterEdit: true,

                       recreateForm: true,

                       afterComplete: function (response) {

                           if (response.responseText) {

                               alert(response.responseText);

                          }

                       }

               });

     

       });

     

    </script>

    Tuesday, January 21, 2020 2:41 PM
  • User753101303 posted

    Hi,

    You should check the doc for this product. You likely have pass parameters or it could take by default form fields found on the current line ???

    Anyway take the time to start from the actual error. You can then look at the relevant place for this exact error... If you look at code and wonder what happens it takes more time to find multiple possible problems and you still don't know which one happens...

    If you see a 500 error page I expect the exception message to be written to the Windows log by default. You'll see for example if this is a NullReferenceException or whatever and you'll be sure where it happens.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, January 21, 2020 3:12 PM
  • User1535942433 posted

    Hi 9peculiar,

    Accroding to your codes,I create a little test and I could get the value of  Model.So I guess your problem is in the script.

    Could you tell us the error  occur before or after entering this line?

    More details,you could refer to below article:

    https://www.c-sharpcorner.com/article/performing-crud-operation-using-jqgrid-in-Asp-Net-mvc/

    Best regards,

    Yijing Sun

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, January 22, 2020 6:44 AM