0

I am having some trouble here. The situation is to update an existing record, at the same time, save a new row if there is no record by searching first the table.

When I am saving a new record, there is no problem. But when I'm trying to update an existing one, there are no changes. I tried to place some breakpoints specifically on the code that do the thing. It just ending up on the line if(!ModelState.IsValid).

Note: Some of the lines are hard-coded for the sake of having some dummy data.

Function for retrieving some data from DB to pass to view model

[HttpGet]
public ActionResult CardNumberAssignment(string empId, int cardNumberId)
{
    var getIdDetails = dbContext.CardNumberAssignments.Where(c => c.CardNumberId == cardNumberId && c.IsActive == true).SingleOrDefault();

    if (cardNumberId == 0) //EMPLOYEE HAS NO CARD NUMBER YET
    {
        var viewModel = new CardNumberQRCodeVM
        {
            CardNumberId = 0,
            CMId = empId,
            OldQRCode = "No QR Code history",
            OldReservedCardNumber = "No Card Number history",
            NewReservedCardNumber = GetRandomCardNumber()
        };

        return View(viewModel);
    }

    else
    {
        if (getIdDetails.CMId != empId) //JUST CHECKING IF THE EMPLOYEE HAS THE CORRECT CARDNUMBERID FROM DB
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }

        var empCardDetails = dbContext.CardNumberAssignments
                                      .Include(c => c.ReservedCardNumber)
                                      .Where(emp => emp.CMId == empId && emp.IsActive == true)
                                      .Select(fields => new CardNumberQRCodeVM
                                      {
                                          CardNumberId = fields.CardNumberId,
                                          CMId = empId,
                                          OldQRCode = fields.QRCode,
                                          IsActive = fields.IsActive,
                                          OldReservedCardNumber = fields.ReservedCardNumber.CardNumber,
                                      }).FirstOrDefault();

        empCardDetails.NewReservedCardNumber = GetRandomCardNumber();

        return View(empCardDetails);
    }
}

Function for adding/editing record

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SaveIdInformation(CardNumberQRCodeVM vm)
{
    if (!ModelState.IsValid)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }

    // JUST ADDING/EDITING SOME CARD NUMBERS....
    else
    {
        if (vm.CardNumberId == 0) //INSERT A NEW ROW FOR NEW CARD NUMBER AND QR CODE
        {
            var newCardNumber = new ReservedCardNumber
            {
                CardNumber = vm.NewReservedCardNumber,
                IsActive = true,
                CreatedDate = DateTime.Now,
                CreatedBy = "Paolo",
                ModifiedDate = DateTime.Now,
                ModifiedBy = "Paolo"
            };

            dbContext.ReservedCardNumbers.Add(newCardNumber);

            var newIdInfo = new CardNumberAssignment
            {
                CardNumberId = newCardNumber.Id,
                QRCode = vm.NewQRCode,
                CMId = vm.CMId,
                IsActive = true,
                CreatedDate = DateTime.Now,
                CreatedBy = "Paolo",
                ModifiedDate = DateTime.Now,
                ModifiedBy = "Paolo"
            };

            dbContext.CardNumberAssignments.Add(newIdInfo);
        }

        else // EDIT EXISTING
        {
            var getEmployeeIdInDb = dbContext.CardNumberAssignments.Single(e => e.Id == vm.CardNumberId);

            getEmployeeIdInDb.ReservedCardNumber.CardNumber = vm.NewReservedCardNumber;
            getEmployeeIdInDb.QRCode = vm.NewQRCode;
            getEmployeeIdInDb.IsActive = true;
            getEmployeeIdInDb.ModifiedDate = DateTime.Now;
            getEmployeeIdInDb.ModifiedBy = "Paolo";
        }

        dbContext.SaveChanges();
    }

    return RedirectToAction("CMDetails", "Admin", new { @empId = vm.CMId });
}

View model

public class CardNumberQRCodeVM
{
    public int CardNumberId { get; set; }

    public string CMId { get; set; }

    [Display(Name = "Existing QR Code")]
    public string OldQRCode { get; set; }

    [Required]
    [Display(Name = "New QR Code")]
    public string NewQRCode { get; set; }

    [Display(Name = "Resigned Cast Member?")]
    public bool IsActive { get; set; }

    public string CreatedBy { get; set; }
    public DateTime CreatedDate { get; set; }
    public string ModifiedBy { get; set; }
    public DateTime ModifiedDate { get; set; }

    public ReservedCardNumber ReservedCardNumber { get; set; }

    [Display(Name = "Old Card Number")]
    public string OldReservedCardNumber { get; set; }

    [Display(Name = "New Card Number")]
    public string NewReservedCardNumber { get; set; }
}
  • When debugging, you can see the property `Errors` of `ModelState` to see what are the errors and why is `ModelState` not valid. Can you try that? – colinD May 24 '19 at 14:32
  • @colinD hi, I can't see any properties of `Errors` of `ModelState`. I can only see the properties of the vm I passed on the `ActionResult`. Am I not doing something to make it show? Sorry for the late response. – Paolo Devoma May 25 '19 at 03:07
  • Yes sorry it's actually a bit more complicated than that. If you put a breakpoint at the line `if (!ModelState.IsValid)` you can view errors like this: https://imgur.com/a/uDRTkaH. You have to check all `Values` of `ModelState` and in each of them you can see the property `Errors` which contains or not the errors that make your model invalid. – colinD May 25 '19 at 13:51
  • @colinD hi, I tried to check every field I am passing and to my shock, the `CreatedBy` and `ModifiedBy` are the fields seem to be causing the error. Until now I'm not done with this. Sigh. – Paolo Devoma May 25 '19 at 13:53
  • Also this https://stackoverflow.com/questions/1352948/how-to-get-all-errors-from-asp-net-mvc-modelstate can make debugging the model state easier. – colinD May 25 '19 at 13:54
  • I'll try what you said by tomorrow. I'll get back to you once done. I need to rest for now. Thank you for your response! :) – Paolo Devoma May 25 '19 at 14:06
  • @colinD hi, I already resolved my issue by checking the null values on the required variables. I wanna say thank you for your help especially to the SS. I just know how to check the errors if there is any. – Paolo Devoma May 26 '19 at 10:29

0 Answers0