TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
Marius Vasile
594
1.9k
144.8k
asp.net core duplicate entry catch error
Jan 19 2021 2:28 PM
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?
Reply
Answers (
1
)
Asp.Net textbox TextChanged event is not firing
asp.net core split a string in two strings