How To Show A Pop Up Or Warning To User If The Db Row Is Going To Be Overwritten In Asp.net Mvc 5
Solution 1:
You can basically repeat the check you use in the POST action currently, but return a simple JSON value instead:
public ActionResult CheckForExistingReferral(ReferralViewModel viewModel)
{
bool hasPreviousRequest = false;
var candidateId = User.Identity.GetUserId();
var referral = _context.Referrals.Where(r => (r.CandidateId == candidateId) && (r.CompanyId == viewModel.CompanyId)).SingleOrDefault();
hasPreviousRequest = referral != null;
return Json(new { hasPreviousRequest = hasPreviousRequest }, JsonRequestBehavior.AllowGet);
}
In your view, you'd do something like:
var data = $('form').serialize();
var url = '@Url.Action("CheckForExistingReferral")';
$.get(url, data)
.done(function(response, status, jqxhr){
if(response.hasPreviousRequest){
// show alert?
}
else{
// post form?
}
});
This is using jQuery's $.get helper, which (mostly) just wraps their $.ajax function. serialize will URL-encode your form values into a format suitable for submitting through the Ajax request, or you can manually construct a JavaScript object, if you prefer.
The .done()
function handles successful responses (anything with a 200 status code). If you want to handle bad/failed requests, you'd add a .fail()
function, something like this:
$.get(url, data)
.done(function(response, status, jqxhr){
})
.fail(function(jqxhr, status, error){
});
error
will contain an object that contains the error details returned from the server. jqxhr
, in both instances, is the XMLHTTPRequest created by jQuery.
Of course, since you'd now be repeating a chunk of code, you should probably refactor this duplicate check into something like a helper method, and then replace the check in both actions.
Since you don't want to allow the form submission unless the user has confirmed the resubmission (or there wasn't a previous submission), you need to prevent the form submission. Here's an example:
// check variable - we'll update this in the handler belowvar canSubmit = false;
$('form').on('submit', function(e){
// Have we checked for resubmissions yet, or has the user approved the resubmit?if(!canSubmit){
e.preventDefault();
var data = $('form').serialize();
var url = '@Url.Action("CheckForExistingReferral")';
$.get(url, data)
.done(function(response, status, jqxhr){
if(response.hasPreviousRequest){
// show alert?if(confirm("You've already applied for this job. Apply again?")){
canSubmit = true;
// $('form').submit(); re-triggers the form submission. // Since the value is now true, the form submission occurs normally
$('form').submit();
}
}
else{
// post form?
canSubmit = true;
$('form').submit();
}
});
}
});
Post a Comment for "How To Show A Pop Up Or Warning To User If The Db Row Is Going To Be Overwritten In Asp.net Mvc 5"