0

I have an ajax form in my MVC application that has two options specified depending on the outcome of the form. These options are 'success' and 'failure'. Each of these options call the respective function as follows:

function Success() {
    ...all good...
}

function Failure() {
    ..that didn't work...
}

In my controller there is a condition that if an item already exists in the database it should return a statuscode of 500 internal server error.

Here is all my code.

View

@using (Ajax.BeginForm("Create", "Offers", new AjaxOptions
{
    OnSuccess = "Success",
    OnFailure = "Failure"
}))
{
    @Html.AntiForgeryToken()
    @Html.HiddenFor(model => model.requirement_idx);
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

    ...form goes here

}

Controller

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(OfferViewModel vm)
{
    bool exists = db.tbl_requirement_vessel_offer
        .Where(c => c.requirement_idx == requirement_idx)
        .Any(o => o.vessel_idx == vessel_idx);

        if (exists)
        {
            return new HttpStatusCodeResult(500, "Already added");
        }
        else
        {
            if (ModelState.IsValid)
            {
                ..Do magic and save...
            }
        }
        return View(vm);
    }

The javascript for the success and failure options are already noted above. Is there anyway I can catch this returned status code in the failure function of my ajax form?

Yanayaya
  • 2,044
  • 5
  • 30
  • 67
  • When you return your StatusCode 500, it trigger the Success or the Failure javascript method ? – Dipiks Jan 05 '17 at 11:39
  • 2
    You can find your answer here. [http://stackoverflow.com/questions/5517813/how-to-use-ajax-beginform-onsuccess-and-onfailure-methods](http://stackoverflow.com/questions/5517813/how-to-use-ajax-beginform-onsuccess-and-onfailure-methods) – Paresh Makwana Jan 05 '17 at 11:46
  • Thank you, I did search but never saw that post. It appears to be inline with what I am looking to do. – Yanayaya Jan 05 '17 at 13:52

0 Answers0