Asad kamal
Asad kamal

Reputation: 45

Getting error in Ajax form from controller in MVC

I am updating some features in a site which is made in asp.NET MVC. I am trying to show an alert when it successfully saves data or when it has some error while saving. My code is something like this:

---------Controller -----

 public JsonResult Insert(string post)
        {
            var posted = Functions.SharePost(post)
            if (posted == true)
            {
                return Json(new { message = "true" });
            }
            return Json(new { message = posted});
        }

---- View code --------

@using (Ajax.BeginForm("Insert", "WebsitePosting", new AjaxOptions { HttpMethod = "POST",  OnComplete = "CheckError(error);" }))
{
  @Html.TextArea("post", new { data_val_required = "The field is required.", data_val = "true", style = "width:800px" })
  <input type="submit" value="Save" class="k-button" />
}

----- Script ----

<script>
function CheckError(error)
{
   if(error == "true"){alert("success");}
   else{alert("faild");}
 }
</script>

Can anyone tell me what I am doing wrong? Thanks in advance.

Upvotes: 0

Views: 91

Answers (1)

Tech Savant
Tech Savant

Reputation: 3766

Update

With your new edits, it should be

if (error.message == "true") { alert('success'); }

End update

Error is an object. Use

if (error) {alert('error');}

or with jquery

if (!jQuery.isEmptyObject(error)) { alert('error'); }

Your script...

<script>
function CheckError(error)
{
   if(error){alert("success");}
   else{alert("faild");}
}
</script>

Upvotes: 1

Related Questions