I want to prevent duplicate entry on post, which works well when there is no parameter for OnGet. Code below
- public void OnGet()
- {
-
- }
-
-
- public async Task<IActionResult> OnPostAsync()
- {
- if (!ModelState.IsValid)
- {
- return Page();
- }
-
- var newWOAL = new WOAssetLocation();
- if (await TryUpdateModelAsync(newWOAL, "WOAssetLocation", s => s.AssetLocation))
- {
- var check = await _context.WOAssetLocations.Where(s => s.AssetLocation == newWOAL.AssetLocation).CountAsync();
- if (check > 0)
- {
- ModelState.AddModelError(string.Empty, "Asset Location already exists");
- return Page();
- }
- if (check == 0)
- {
- _context.WOAssetLocations.Add(newWOAL);
- await _context.SaveChangesAsync();
- return RedirectToPage("/WO/Location/Index");
- }
- }
-
- return null;
- }
The duplicate is captured and I have error mesage displayed on page. However, when I have OnGet with parameter is not working
- public async Task<IActionResult> OnGetAsync(string id)
- {
- if (id == null)
- {
- return NotFound();
- }
- var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
- var idorg = await _context.UsersData.Where(u => u.Id == userId).Select(u => u.OrgID).SingleAsync();
- OrgID = idorg;
- WOAssetLocation = await _context.WOAssetLocations.Where(m => m.WOALId == id).FirstOrDefaultAsync();
-
- if (WOAssetLocation == null)
- {
- return NotFound();
- }
- return Page();
- }
- public async Task<IActionResult> OnPostAsync()
- {
- if (!ModelState.IsValid)
- {
- return Page();
- }
- var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
- var idorg = await _context.UsersData.Where(u => u.Id == userId).Select(u => u.OrgID).SingleAsync();
- var newWOAA = new WOAssetAsset();
- if (await TryUpdateModelAsync(newWOAA, "WOAssetAsset",
- s => s.WOALId,
- s => s.OrgID,
- s => s.AssetID,
- s => s.AssetName,
- s => s.AssetManufacturer))
- {
- var check = await _context.WOAssetAssets.Where(s => s.AssetID == newWOAA.AssetID).CountAsync();
- if (check > 0)
- {
- ModelState.AddModelError(string.Empty, "Asset ID already exists");
- return Page();
- }
- if (check == 0)
- {
- _context.WOAssetAssets.Add(newWOAA);
- await _context.SaveChangesAsync();
- return RedirectToPage("/WO/Asset/Index", new { id = newWOAA.WOALId });
- }
- }
-
- return null;
- }
the application is throwing an error message and halt.
What should be the approach?