I have a Web Api in which I have this code
#{
AjaxOptions addAjaxOpts = new AjaxOptions
{
// options will go here
OnSuccess = "getData",
OnFailure="selectView('add')",
HttpMethod = "Post",
Url = "/api/AccountManage/CreateAccount"
};
}
In the controller :
[HttpPost]
public void CreateAccount(CollaborateurModel item)
{
try{}
catch{
// return failure
}
}
I need to implement failure part to execute OnFailure method .
So how can I accomplish this task?
You can start by using Json Result (MSDN ref.)
Snippet example:
[HttpPost]
public ActionResult CreateAccount(CollaborateurModel item)()
{
try{
//do operations that may fail
var response = new { Success = true};
return Json(response );
}catch{
var errorResponse= new { Success = false, ErrorMessage = "error"};
return Json(errorResponse);
}
}
Then on the client side you call the controller using JQuery:
$(function () {
$(".test-link").click(function (e) {
$.post("controllerName/CreateAccount", function (data) {
if (data.Success == true) {
alert("Success");
}
else {alert(data.ErrorMessage);}
});
return false;
}).fail(function() {
alert( "error" );
});
});
The fail function on Jquery will handle communication problems that you may have with client-server.
More info about JQuery you can find it here.
Depending on your desired response status code, you can use the BadRequest, NotFound or InternalServerError result classes. Each of these have a constructor that has an optional parameter for an error message.
[HttpPost]
public IHttpActionResult CreateAccount(CollaborateurModel item)
{
try
{
// Do your thing
}
catch
{
// Return a HTTP 400 result
return BadRequest("This is an error message");
}
}
Related
I am learning web development. And I just want to make a simple AJAX GET call in ASP.Net MVC Application and I want visualize how it works. But I am not able to do so. I am a beginner and I could have done any silly mistakes. But as of now there are no errors in my code.
Below is what I have:
So, I have a Index.cshtml file which is already loaded. Now in that page I want to make an Ajax GET call to one of the function that I have written in the HomeController and action name is Test. I just want to hit the breakpoint in that Test Action of Homecontroller and return something back to the Success of AJAX Call.
In HomeController I have below Action
[HttpGet]
public ActionResult Test()
{
return View("hello");
}
jQuery
$.ajax({
url: '/Home/Test',
type: 'GET',
success: function (html) {
alert(html);
},
error: function (error) {
$(that).remove();
DisplayError(error.statusText);
}
});
}
Confusion: Do I need to create a cshtml for Test. But I actually do not want that. I just want the Test Action to return me one data. And I will display that data in my Already opened Index.csthml file.
Error: No error but I am not able to hit the breakpoint in Test Action of controller. Kindly note that Success of AJAX is hitting but I do not see any data. But I am sure it did not hit the test Action breakpoint.
Change your action method like this
[HttpGet]
public JsonResult Test()
{
return Json("myContent",JsonRequestBehavior.AllowGet);
}
And in your success method in 'html' variable you will get back "myContent".
Example :
function RemoveItem(ItemId) {
if (ItemId && ItemId > 0) {
$.ajax({
cache: false,
url: '#Url.Action("RemoveItem", "Items")',
type: 'POST',
data: { id: ItemId },
success: function (result) {
if (result.success == true) {
$("#CartItemGridDiv").load('#Url.Content("~/User/Items/CartItemGrid")');
alert('Item Removed successfully.');
}
else {
alert('Item not removed.');
}
},
error: function (result) {
alert('Item not removed.');
}
});
}
}
public ActionResult RemoveItem(int id)
{
if (id > 0)
{
bool addToChart = false;
addToChart = Utilities.UtilityClass.RemoveItem(id);
if (addToChart)
{
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
}
return Json(new { success = false }, JsonRequestBehavior.AllowGet);
}
public ActionResult CartItemGrid()
{
List<CartItems> oItemList = (List<CartItems>)Session[MvcMAB.StringConst.CartItemSession];
return View(oItemList);
}
Since you don't want to return a view, you might need to return Json() instead of View()
You need to Allow Get in the action. Like that:
public ActionResult SomeGetAction(int? id)
{
//Some DB query here
var myJsonList = myListQuery;
return Json(myJsonList, JsonRequestBehavior.AllowGet);
}
Or in case of just Simple string response:
public ActionResult SomeGetAction()
{
return Json("My String", JsonRequestBehavior.AllowGet);
}
I would recommend renaming html into response.
Also change that to this in Error Response section.
$.ajax({
url: '/Home/Test',
type: 'GET',
success: function (response) {
alert(response);
},
error: function (error) {
$(this).remove();
DisplayError(error.statusText);
}
});
Enjoy.
C#:
public JsonResult Test()
{
return Json("hello");
}
Jquery:
$.ajax({
url: '/Home/Test',
type: 'Post',
dataType: 'json',
success: function (html) {
alert(html);
},
error: function (error) {
alert(error);
}
});
I have a ajax form in which I would like to call two different javascript functions, one for success and one for failure. In both of these calls, I pass data back from the server to the javascript. Please note the following:
I have this in my view
#using (Ajax.BeginForm("MyAction", null,
new AjaxOptions
{
HttpMethod = "POST", // HttpPost
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "myDiv",
OnSuccess = "callSuccess(data.msg)",
OnFailure = "callFailure(data.msg)",
}, new { #class = "form-inline" }))
{
... // my content
}
My controller has the following logic when return the post.
public ActionResult MyAction(string myString)
{
...
// If error occurred
return Json(new { success = false, msg= "Fail" });
...
// If no errors
return Json(new { success = true, msg= "Success" });
}
No matter what is returned, OnSuccess is the only one that gets called. What is the proper way to call OnFailure?
Consider Using HTTP Status Codes
You could consider returning the appropriate HTTP status code that corresponds with the type of error you want to trigger (i.e. Unauthorized, Bad Request, etc.) by returning an HttpStatusCodeResult object :
// If an error occurred...
if(error)
{
// Indicate your code and error message. This uses the Bad Request status (400)
return new HttpStatusCodeResult(400, "Something went wrong...");
}
Handling This Client-Side
If you didn't want to do this, you could consider defining a single result event (i.e. OnSuccess = "call(data);) and then within that event, check your success property to determine what to do :
function call(data){
if(data.success){
callSuccess(data.msg);
}
else{
callFailure(data.msg);
}
}
With the help from Rion Williams post, I was able to call both functions. More importantly, I figured out how to access and display the desired message upon success/failure:
My controller
public ActionResult MyAction(string myString)
{
...
// If error occurred
return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Error occurred!");
...
// If no errors
return Json(new { success = true, msg= "Success" });
}
My view:
#using (Ajax.BeginForm("MyAction", null,
new AjaxOptions
{
HttpMethod = "POST", // HttpPost
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "myDiv",
OnSuccess = "callSuccess(data.msg)",
OnFailure = "callFailure(error)", // error = "Error occurred!"
}, new { #class = "form-inline" }))
{
... // my content
}
Yes it will always call OnSuccess.
But you can check your success Property inside onSuccess function.
OnSuccess : function (data)
{
if(success)
{
alert('Json Return Success')
}
else
{
alert('json Result False')
}
}
Otherwise you have to send error status as Rion Williams mention
My Jquery ajax call -
var formdata = $('#emailrequest').serializeArray();
// Ajax call to server
$.ajax({
url: sitePath + 'supply-chain-pressure/ProcessEmailrequest',
type: 'POST',
data: formdata,
sucess: function(data) {
alert(data.sucess);
},
error: function() {
alert('error');
}
});//End Ajax
My controller -
public ActionResult ProcessEmailrequest()
{
// some code
// retun the response
return Json(new {success = true});
But all is get is error in alert . Where am I going wrong? Please help . I just need to return a confimation from controller , be it any format.
You spelled success wrong so it will never hit. It should work with the ActionResult but a JsonResult is better.
var formdata = $('#emailrequest').serializeArray();
// Ajax call to server
$.ajax({
url: sitePath + 'supply-chain-pressure/ProcessEmailrequest',
type: 'POST',
data: formdata,
success: function(data) {
alert(data.sucess);
},
error: function() {
alert('error');
}
});//End Ajax
Try to set your controller method return type to JsonResult instead of ActionResult, so:
public JsonResult ProcessEmailrequest()
{
// some code
// retun the response
return Json(new {success = true});
}
If that doesn't help set your ajax error function to receive following parameters:
error: function (xhr, ajaxOptions, thrownError) {
...
}
Then debug in browser and set a break point to error function and in the xhr object (responseText property) you'll be able to see exact error.
you shoudn't return json like that. use [ ] instead of {}
public JsonResult ProcessEmailrequest()
{
// some code
// retun the response
return Json(new [success = true]);
}
I am new to .NET MVC so please bear with me.
I wrote a function that gets triggered when there is a blur action on the textarea control:
function extractURLInfo(url) {
$.ajax({
url: "/Popup/Url",
type: "POST",
data: { url: url },
complete: function (data) {
alert(data);
},
success: function (data) {
alert(data);
},
async: true
})
.done(function (r) {
$("#url-extracts").html(r);
});
}
jQuery(document).ready(function ($) {
$("#input-post-url").blur(function () {
extractURLInfo(this.value);
});
});
This works fine and will hit the controller:
[HttpPost]
public ActionResult Url(string url)
{
UrlCrawler crawler = new UrlCrawler();
if (crawler.IsValidUrl(url))
{
MasterModel model = new MasterModel();
model.NewPostModel = new NewPostModel();
return PartialView("~/Views/Shared/Partials/_ModalURLPartial.cshtml", model);
}
else
{
return Json(new { valid = false, message = "This URL is not valid." }, JsonRequestBehavior.AllowGet);
}
}
I get the intended results if the URL is valid; it will return a partialview to the .done() function and I just display it in code. However, if the URL is not valid i want it to hit either complete, success, or done (I have been playing around to see which it will hit but no luck!) and do something with the returned data. I had it at some point trigger either complete or success but the data was 'undefined'. Can someone help me out on this?
Thanks!
In both cases your controller action is returning 200 status code, so it's gonna hit your success callback:
$.ajax({
url: "/Popup/Url",
type: "POST",
data: { url: url },
success: function (data) {
if (data.message) {
// Your controller action return a JSON result with an error message
// => display that message to the user
alert(data.message);
} else {
// Your controller action returned a text/html partial view
// => inject this partial to the desired portion of your DOM
$('#url-extracts').html(data);
}
}
});
But of course a much better and semantically correct approach is to set the proper status code when errors occur instead of just returning some 200 status code:
[HttpPost]
public ActionResult Url(string url)
{
UrlCrawler crawler = new UrlCrawler();
if (crawler.IsValidUrl(url))
{
MasterModel model = new MasterModel();
model.NewPostModel = new NewPostModel();
return PartialView("~/Views/Shared/Partials/_ModalURLPartial.cshtml", model);
}
else
{
Response.StatusCode = 400;
Response.TrySkipIisCustomErrors = true;
return Json(new { valid = false, message = "This URL is not valid." }, JsonRequestBehavior.AllowGet);
}
}
and then in your AJAX call you would handle those cases appropriately:
$.ajax({
url: "/Popup/Url",
type: "POST",
data: { url: url },
success: function (data) {
$('#url-extracts').html(data);
},
error: function(xhr) {
if (xhr.status == 400) {
// The server returned Bad Request status code
// => we could parse the JSON result
var data = JSON.parse(xhr.responseText);
// and display the error message to the user
alert(data.message);
}
}
});
Also don't forget that you have some standard way of returning your error messages you could subscribe to a global .ajaxError() handler in jQuery instead of placing this code in all your AJAX requests.
I have an ajax call to my controller, which in turn calls a service which returns true or false. I cannot seem to figure out why this always triggers my success function when it returns from controller to view.
Controller
[HttpGet]
public JsonResult TagUnit(int id, string selectedItem)
{
try
{
var result = UnitClient.TagUnit(id, selectedItem);
if (!result)
{
throw new InvalidOperationException();
}
return Json(new {success = true}, JsonRequestBehavior.AllowGet);
}
catch (Exception e)
{
return Json(new {success = false}, JsonRequestBehavior.AllowGet);
}
}
Cshtml - Javascript - Ajax
.on("select2-selecting", function (e) {
var url = '#Url.Content("~/UnitDetails/TagUnit/" + Model.ViewUnitContract.Id)';
var id = e.val;
var tagName = e.object.text;
console.log(id + " : " + tagName);
$.ajax({
url: url,
data: { selectedItem: tagName },
type: 'GET',
dataType: 'json',
success: function () {
alert('Success');
},
error: function () {
alert('Error');
}
});
}).select2('val', ['1', '2']);
What am I missing here?
You should validate server result data in success method.
$.ajax({
url: url,
data: { selectedItem: tagName },
type: 'GET',
dataType: 'json',
success: function (data) {
if (data != null && data.success) {
alert('Success');
} else {
alert('Error');
}
},
error: function () {
alert('Error');
}
});
Error method calls if on the server occurred 500 error or server is not avaliable, etc.
I think that if you throw an exception, it will still return with a success status code. So what I have done is create an ajax call error handler attribute that can be attached to your MVC methods. It will capture uncaught exceptions, set an error status code and give a generic error message (and also log to Elmah). The attribute is below
public class HandleJsonErrorAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
var serviceException = filterContext.Exception as Exception;
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
filterContext.Result = new JsonResult
{
Data = new
{
errorMessage = "Generic error message",
errorType = 0
},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
var kayttaja = (Kayttaja.TKayttajantiedot)filterContext.HttpContext.Session["userKayttajanTiedot"];
Global.HandleApplicationError(serviceException, kayttaja);
filterContext.ExceptionHandled = true;
// Log to elmah
//Elmah.ErrorSignal.FromCurrentContext().Raise(filterContext.Exception);
}
}
Then decorate your action methods that should only be called by Ajax with: [Campus.Attribuutit.HandleJsonError]
The important line for triggering the error handler in the ajax call object is HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError
Don't know if I understand your question properly.
success function in Ajax will execute if the request is successful. And error function will execute if the request fails. You have to check what the server returns inside of the success function.
http://api.jquery.com/jQuery.ajax/