ASP.NET # MVC # 20 – Pass/Send Object from Server to JavaScript method on Ajax Form’s onSuccess Event using JSON(JavaScript object notation).
Hi Friends,
Many times we come across the situation where we need to pass the class object from server to the JavaScript function on onSuccess method of Ajax.BeginForm.
OnSuccess gets called only if the request was successful.
In this post we will see how to pass the object from the method on controller to the client side JavaScript method.
-> We have our Ajax Form and JavaScript method as follows:
- <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
- <script type="text/javascript">
- function funSuccess(context) {
- debugger;
- var html = context.get_data();
- var obj = $.parseJSON(html);
- alert(obj.SuccessMessage);
- }
- </script>
- <%using (Ajax.BeginForm("PostFormMethod", "Search", new AjaxOptions { OnSuccess = "funSuccess" }))
- { %>
- <h1>
- Hello Ajax</h1>
- <input type="submit" id="btnSubmit" />
- <%} %>
- </asp:Content>
As you see in the code above we have Ajax.BeginForm which has PostFormMethod as its Action name and Search as its controller name , and funSuccess is the JavaScript method which is being called on onSuccess event of the form.
-> We have our code on Controller side as follows
- [HttpPost]
- public string PostFormMethod()
- {
- Result obj = new Result();
- obj.SuccessMessage = "Record Saved Successfully!!!";
- System.Web.Script.Serialization.JavaScriptSerializer oSerializer =
- new System.Web.Script.Serialization.JavaScriptSerializer();
- return oSerializer.Serialize(obj);
- }
In the above method we are returning the Serialized class object by using the JavaScriptSerializer which is returning the string in serialize format to the onSuccess method of the form.
-> The JavaScript method funSuccess deserialize the object using $.parseJson jquery function which will return you the object as you see in the following image.
Thanks,
Hope this will help!!!
![]()