mvc3 ajax submission on the controller side. How? - asp.net-mvc-3

I don't understand once button clicked
How to handle ajax call on the server side so that my DataAnnotation work
and I get success or error message.
<script src="../../../../Content/Scripts/jquery-1.4.4-vsdoc.js" type="text/javascript"></script
<script type="text/javascript">
$(function ()
{
$("#createButton").click(function ()
{
var profile = {
FirstName: $("#FirstName").val(),
LastName: $("#LastName").val(),
Email: $("#Email").val()
};
$.ajax({
url: "/Profile/Create",
type: "Post",
data: JSON.stringyfy(profile),
dataType: "json",
contentType: "Application/json; charset=utf-8",
success: function () {
$("#message").html("Profile Saved.");
},
error: function () {
$("#message").html("Error occured");
}
});
return false;
});
});
</script>
//Server side
public ActionResult Create(string confirmButton, CreateViewModel userVm)
{
if (confirmButton != "Create Profile") return RedirectToAction("Index");
if (!ModelState.IsValid)
return View("Create", userVm);
User user = new User();
Mapper.Map(userVm, user);
_repository.Create(user);
return RedirectToAction("Details", new { id = user.UserId });
}

If I remember correctly (it's been a while since I played with jquery), the success and error are indicative of the return value of the actual HTTP request itself. For example, if you hit a 404, you'd get an error message.
Regardless of whether or not a profile was created successfully through your page logic, if the request itself was processed, then the success message will be hit - you need to interpret the return value yourself at that point.

Try returning a JsorResult in place of redirecting to a view, then client side, parse the JsonResult and act accordingly.
[HttpPost]
public JsonResult DeleteDoc(int Id, int DocCode, SomeObject Model)
{
try
{
// Check annotations stuffs
if (!Model.IsValid) {
var jsonDataM = new { ExitCode= -100, message = "Invalid Model" };
return Json(jsonDataM, JsonRequestBehavior.DenyGet);
}
// My logic in here
var jsonData = new { ExitCode= 0, message = "Everything's ok" };
return Json(jsonData, JsonRequestBehavior.DenyGet);
}
catch (Exception e)
{
var jsonData2 = new { ExitCode= -1, message = "Everything's Ko" + e.Message };
return Json(jsonDat2a, JsonRequestBehavior.DenyGet);
}
}
in the OnSuccess callback you can refer to this with:
<script type="text/javascript">
function MyAjaxCallBack(context) {
var code = context.ExitCode;
if (code != 0) {
alert (context.message);
}
}
</script>
Please note that this code is simplified. When managing the IsValid on Model, I usually iterate del ModelState in order to build up a message.

Related

How to display update content after posting data by ajax in asp.net core entity framework core

I want to display update content after posting data by jquery ajax. I tried it but not display data.
here is my code...
jquery ajax
$(document).ready(function () {
$('#paid').click(function () {
var pid = $('#pid').val();
var amt = $('#amt').val();
var payType = $('#payType').val();
$.ajax({
type: "POST",
url: "/Reception/Registration/AddPaidBalance",
data: { PatientId: pid, PaidAmt: amt, PaymentType: payType },
success: function (data) {
}
});
});
})
controller
[HttpPost]
public async Task<IActionResult> AddPaidBalance(PatientBilling patientBilling)
{
if (ModelState.IsValid)
{
_db.PatientBilling.Add(patientBilling);
await _db.SaveChangesAsync();
//return RedirectToAction("Details", "Registration", new { area = "Reception", id = patientBilling.PatientId });
//return RedirectToAction("Details", "Registration", new { patientBilling.PatientId});
}
return View();
}
help me out from this issue.
Based on your code, you make ajax request to post data of PatientBilling to action method. To display new-added PatientBilling information on Details page after the request completes successfully, you can do redirection in success callback function, like below.
<script>
$(document).ready(function () {
$('#paid').click(function () {
var pid = 1;//$('#pid').val();
var amt = "amt";//$('#amt').val();
var payType = "type1";//$('#payType').val();
$.ajax({
type: "POST",
url: "/Reception/Registration/AddPaidBalance",
data: { PatientId: pid, PaidAmt: amt, PaymentType: payType },
success: function (data) {
window.location.href = "#Url.Action("Details", "Registration", new { Area = "Reception"})" + "?patientId=" + pid;
}
});
});
})
</script>
Details action
public IActionResult Details(int patientId)
{
// code logic here
// get details of PatientBilling based on received patientId
// ...
return View(model);
}

asp.net mvc index action is called automatically after ajax

I have an action that creates a record in the database:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Name,Description")] SampleViewModel sampleVM)
{
try
{
_service.Add(sampleVM);
this.ShowMessage(new ToastMessage(ToastType.Success, "Record Added", ToastrDisplayType.TopLeft));
}
catch (Exception ex)
{
this.ShowMessage(new ToastMessage(ToastType.Error, ex.Message, ToastrDisplayType.TopLeft));
return Json("failed");
}
return Json("success");
}
this Action is called by AJAX:
$().ready(function () {
$("#btnSave").click(function () {
var serviceURL = '';
var sample = {
"Id": $('#hdnId').val(),
"Name": $("#txtName").val(),
"Description": $("#txtDescription").val(),
};
if (save_method == 'add') {
serviceURL = '#Url.Action("Create", "Samples")';
}
else if (save_method == 'edit') {
serviceURL = '#Url.Action("Edit", "Samples")';
}
$.ajax({
type: "POST",
url: serviceURL,
data: addRequestVerificationToken(sample),
success: function (data, textStatus, jqXHR) {
handleAjaxMessages();
},
});
});
});
The problem is that the Index Action is called automatically after the Create Action:
[HttpGet]
public ActionResult Index()
{
return View();
}
Fiddler snapshot
The Toast message is not displayed because the Index Action is called, How can I call the Create Action only (without calling the Index Action)?
So your "#btnSave" is a <button type="submit" /> button. The browser will do the following in order:
Invoke your own click handler, that you have shown in your code.
Post the <form> that your button is in to the server and reload the page with the answer that it gives.
You have two options: either you remove the form and have a regular <button> (without type="submit"), or you modify your click handler a little:
$("#btnSave").click(function (event) {
event.preventDefault(); // notice this line
var serviceURL = '';

MVC OutputCache JsonResult returns html

I have the following controller:
[HttpPost]
[OutputCache(Duration=3600, VaryByParam="*", Location=OutputCacheLocation.Server)]
public JsonResult FreeTextQuery(SearchFiltersQuery filters)
{
Trace.TraceInformation("Entering method SearchController.FreeTextQuery");
SearchResults aResults = new SearchResults();
if (ModelState.IsValid)
{
try
{
ClaimsPrincipal user = User as ClaimsPrincipal;
aResults = _objectRepository.GetFullTextResults(filters, user);
}
catch (Exception ex)
{
if (!(#Url == null))
{
return Json(new { redirectUrl = #Url.Action("ShowError", "Error", new { message = ex.Message }), isRedirect = true });
}
}
}
Trace.TraceInformation("Exiting method SearchController.FreeTextQuery");
return Json(aResults);
}
which is called by the following ajax function
function GetResults(aFilters) {
var aEndPointUrl = "/Search/FreeTextQuery";
var jSonString = JSON.stringify(aFilters);
$.ajax({
type: 'POST',
url: aEndPointUrl,
traditional: true,
contentType: 'application/json; charset=utf-8',
data: jSonString,
success: function (data) {
// omitted for brevity
},
error: function (xhr, ajaxOptions, error) {
window.location.href = "/Error/ShowError?message=" + encodeURIComponent("Onbekende fout bij het zoeken.");
}
});
This code works fine without the OutputCache attribute on the controller. With it it always hits the error function of the ajax call and I see that the response is not JSON but HTML content (error is a parser error therefore).
What could be going wrong with the outputcaching and how do I get it working correctly? I've tried many ways of supplying VaryByParams but they all have the same result.
This post revealed the answer. The problem was outputting the trace to the page: page outputcache not working with trace

MVC3 ajax action request: handling answer

I'm doing an Ajax request to an MVC3 action and I want to process the JsonResult in the success or error function.
Currently the behaviour is strange: Before hitting my breakpoint in the action it hits the error function.
Can anyone help me please and has a hint?
My view:
<form id="myForm">
//fields go here...
<button id="myButton" onclick="myFunction();">ButtonName</button>
</form>
The ajax call:
function myFunction() {
if ($('#myForm').valid() == false) {
return;
}
var data = {
val1: $("#val1").val(),
val2: $("#val2").val()
};
var url = "/Controller/Action";
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
cache: false,
data: data,
success: function (data, statusCode, xhr) {
alert('1');
if (data && data.Message) {
alert(data.Message);
alert('2');
}
alert('3');
},
error: function (xhr, errorType, exception) {
alert('4');
var errorMessage = exception || xhr.statusText;
alert("There was an error: " + errorMessage);
}
});
return false;
}
My action:
[HttpPost]
public ActionResult Action(Class objectName)
{
var response = new AjaxResponseViewModel();
try
{
var success = DoSomething(objectName);
if (success)
{
response.Success = true;
response.Message = "Successful!";
}
else
{
response.Message = "Error!";
}
}
catch (Exception exception)
{
response.Success = false;
response.Message = exception.Message;
}
return Json(response);
}
If you look in the ajax call I get directly the alert #4 and only then the action gets called which is too late. Unfortunately the exception is null. Directly after that the view gets closed.
You are not preventing the default onclick behavior. Can you try the following instead?
onclick="return myFunction()"

How to send ajax request to check session timeout and render relogin message in grails?

I want to display a message to the user saying, "you're logged out re-login please!" when session is timed-out, sending an ajax request each time. If session timer ends i want to send final ajax request displaying above message. But the problem here is i don't know where should i have to keep my ajax and jquery codes and since i don't have much knowledge about ajax request, can anyone explain this process with codes. In siple my requirement is like of what facebook shows on session time out, or when any one tab in case of multiople tabs are logged out. I'm working on grails project.
Do your ajax request like this
$.ajax({
url:url,
type:"POST", // or get
data:parameters,
success: function(data) {
// do procedure if success
}
error : function(xhr, type, error){
// do procedure if fail
// may be send a message to the server side to display a message that shows session timeout
}
});
Handle your session timeout in the error function
I did it myself and this is the js code for it "gracefulSession.js" and call this javascript at the page where you are going to embed your html code..
function checkSessionStatus() {
var lStorage = getLocalStorage();
if (lStorage) {
//lStorage.setItem('poleTime',new Date());
var poleTime = lStorage.getItem("poleTime");
var parsedTime;
try {
parsedTime = new Date(poleTime);
} catch (e) {}
//alert(new Date()-parsedTime)
//alert(new Date())
//alert(parsedTime)
//3900000 = 1H5M
if (parsedTime && (new Date() - parsedTime) < 3900000) {
//alert('NCATCH'+parsedTime);
} else {
//alert('POINT');
poleSessionStatus();
}
}
}
function setlatestPoleTIme() {
//alert("SETTING POLE TIME");
var lStorage = getLocalStorage();
if (lStorage) {
lStorage.setItem('poleTime', new Date());
}
}
function setCheckSessionTimer() {
var lStorage = getLocalStorage();
var isLoggedOut = false;
if (lStorage) {
if (lStorage.getItem('isLoggedOut') == 'true') {
isLoggedOut = true;
}
}
//console.log('checkingIfLoggedOut');
if (!isLoggedOut) {
setTimeout("setCheckSessionTimer();", 5000);
//console.log("NOPT LO");
$('#LoggedoutMessage').hide();
checkSessionStatus();
} else {
setTimeout("setCheckSessionTimer();", 5000);
//console.log("KO");
//alert("You're Logged Out from other tab");
$('#LoggedoutMessage').show();
}
}
function logout() {
//alert("LOGGIN OUT")
var lStorage = getLocalStorage();
if (lStorage) {
lStorage.setItem('isLoggedOut', 'true');
}
}
function resetLoggedOutFLag() {
var lStorage = getLocalStorage();
if (lStorage) {
lStorage.removeItem('isLoggedOut');
}
}
function getLocalStorage() {
var storage, fail, uid;
try {
uid = new Date;
(storage = window.localStorage).setItem(uid, uid);
fail = storage.getItem(uid) != uid;
storage.removeItem(uid);
fail && (storage = false);
} catch (e) {}
return storage
}
Now, HTML code to embed ,
<div id="LoggedoutMessage" style="display:none;position:absolute;background:black;height: 200%;width:100%;top: 0;z-index: 10000;opacity: 0.9;">
<div id="login_box" style="position:fixed;left:38%;top:30%; padding:10px; width: 365px;margin: 0 auto;border: 0px solid #CCC;margin-top: 35px;height: 150px;background: white; border-radius:3px;">
<div id="login_title">
<h1>You have been logged out.</h1>
</div>
<div id="reLogin">
<p>Please login to continue.</p>
<g:link controller="dashBoard" action="index" target="_blank" onclick="logout();">Login</g:link>
</div>
</div>
</div>
Finally where you keep your html,keep this javascript code at top of it embedding script tag:
function poleSessionStatus() {
jQuery.ajax({
type: 'POST',
data: '',
url: '<g:createLink action="ajaxCheckSession" controller="dashBoard"/>',
success: function (data, textStatus) {
//setTimeout ( "checkSession();", 5000);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$('#LoggedoutMessage').show();
},
complete: function (XMLHttpRequest, textStatus) {
$.unblockUI();
}
});
}

Resources