pavanarya

Let us share the knowledge

Making Ajax Calls in MVC3 Razor View and Calling Methods Present in Controller from cshtml

with 6 comments

Hi,
In the first look i felt that Microsoft is trying to make use of Jquery for ajax calls in MVC3 to more extent than its own ajax tool kit.

So in this post let us see on how we can call methods inside the controller using Jquery.

Calling Methods inside a controller using Jquery Get method

In my previous post we saw how to call a method present in the code behind file using scriptmanager in web forms.

In order to call the methods present in the controller from cshtml(razor view) we can make use of Jquery’s get method.

@{
        //Layout = null;
}

<script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
        	<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
        <script type="text/javascript">
            function pavanGet() {
                $.get('First/returnJsonData', function (data) {
                    alert(data.firstname);
                }
                );
            }

</script>
    
  @using (Html.BeginForm())
  {
      <input type=button id="btn" value="Button1" onclick="pavanGet()" />
}

So what are we doing here i created a button and in the onclick event i am calling PavanGet() javascript function.
Inside the javascript function i am making use of my favorite jquery method get().

For get method we are passing two parameters.
1.Some string
2.call back function that actually contains the data returned by our method in the controller.once the call to the url mentioned in the first parameter is done our callback function will be executed immediately.

So what is that “some string”.
In general the some string can be
1. A web service url(webservice.asmx\webmethod)
2.In our case we can call our methods present in the controller

“First/returnJsondata” specifies our Controller(First) and the method returnJsonData inside our controller.

Creating the method inside the Controller that returns data to our get request

In my previous posts related to MVCMVC part1,MVC part2 all my methods inside the controller are having a return type ActionResult which renders a view.

Now let us introduce a new return type called JsonResult. JsonResult represents a class that returns json content to a request.
So we are going to create a method called returnJsonData() that returns Json data when we call from our jquery method $.get()

public JsonResult returnJsonData()
        {
            middlename = "pavanjj";
            Models.MyModel mod = new Models.MyModel();
            mod.firstname = "pavan";
            mod.lastname = "arya";
            return Json(mod,JsonRequestBehavior.AllowGet);
        }

Here i am trying to create an object to my class and then passing into to the method Json() that serializes MyModel object.

Note: The most important thing here is we are supposed to pass JsonRequestBehavior.AllowGet to Json(). If we dont pass this parameter then there would be a security restriction that prevents get request and in the browser we will get an error stating

Failed to load resource: the server responded with a status of 500 (Internal Server Error)

Note: we don’t have anything like JsonRequestBehavior.AllowPost.

So how do we make post requests to our method and get some data

So in order to make post requests from our javascript i am trying to make use of $.post method.

@{
        //Layout = null;
}
@model MvcApplication2.Models.MyModel

<script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
        	<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
        <script type="text/javascript">
            
            function pavanPost() {
                $.post('First/JsonDataPost', function (data) {
                    alert(data.firstname);
                }
                );
            }
</script>
Html.BeginForm())
  {
      <input type=button id="btn1" value="Button2" onclick="pavanPost()" />
}


Here i am creating a button Button2 and in the onclick event i am calling pavanPost() that in turn calls $.post with two parameters. The first one is ControllerName/MethodName and the second one is callback method.

When we don’t have anything like JsonRequestBehavior.AllowPost. equivalent to JsonRequestBehaviour.AllowGet how do we make post request efficiently without getting the error
Failed to load resource: the server responded with a status of 500 (Internal Server Error)

The answer is simple we will not pass any second parameter JsonRequestBehaviour.AllowGet to the Json() that actually serializes and returns data.
And we will decorate the method with an attribute called [AcceptVerbs(HttpVerbs.Post)]

[AcceptVerbs(HttpVerbs.Post)]
        public JsonResult JsonDataPost()
        {
            middlename = "pavanjj";
            Models.MyModel mod = new Models.MyModel();
            mod.firstname = "pavan";
            mod.lastname = "arya";
            return Json(mod);
        }

Over all code and quick recap

FirstController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcApplication2.Controllers
{
    public class FirstController : Controller
    {
        //
        // GET: /First/
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Index()
        {
            Models.MyModel mod = new Models.MyModel();
            mod.firstname = "pavan";
            mod.lastname = "arya";
            ViewResult v = View("myFirstView", mod);
            return v;
        }

        
        public JsonResult returnJsonData()
        {
            middlename = "pavanjj";
            Models.MyModel mod = new Models.MyModel();
            mod.firstname = "pavan";
            mod.lastname = "arya";
           return Json(mod,JsonRequestBehavior.AllowGet);
        }
        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult JsonDataPost()
        {
            middlename = "pavanjj";
            Models.MyModel mod = new Models.MyModel();
            mod.firstname = "pavan";
            mod.lastname = "arya";
            return Json(mod);
        }

    }
}

here i am having 3 methods
.
1st methods returns a view called myFirstView which is present in Controller/First/myFirstView.cshtml folder
2nd method returnJsonData returns json data to the get request from javascript.
3rd method jsonDataPost returns data to the post request from javascript.

MyFirstView.cshtml:

@{
        //Layout = null;
}
@model MvcApplication2.Models.MyModel

<script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
        	<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
        <script type="text/javascript">
            function pavanGet() {
                $.get('First/returnJsonData', function (data) {
                    alert(data.firstname);
                }
                );
            }

            function pavanPost() {
                $.post('First/JsonDataPost', function (data) {
                    alert(data.firstname);
                }
                );
            }
</script>

  @using (Html.BeginForm())
  {
      <input type=button id="btn" value="Button1" onclick="pavanGet()" />
      <input type=button id="btn1" value="Button2" onclick="pavanPost()" />
}

Here i am having 2 buttons Button1 and Button2. Button1 makes get request and Button 2 makes post request using jquery get and post methods respectively.

Thanks,
Pavan

About these ads

Written by pavanarya

June 16, 2012 at 2:24 pm

Posted in Jquery, MVC

6 Responses

Subscribe to comments with RSS.

  1. Great Article

    We can also submit our .net related links on http://www.dotnettechy.com to improve traffic.

    The dotnettechy.com is a community of .Net developers joined together to learn, to teach, to find solutions, to find interview questions and answers, to find .net website / blog collection and to have fun programming.

    Micle

    June 17, 2012 at 9:05 pm

  2. how can i return list and read the list in view, using ajax???

    sandyseo

    June 26, 2012 at 10:15 am

    • Hi Sandy can you please elaborate your requirement.Thanks,
      Pavan

      pavanarya

      June 26, 2012 at 3:03 pm

  3. Where exactly did u actually obtain the concepts to create ““Making
    Ajax Calls in MVC3 Razor View and Calling Methods Present in Controller from cshtml pavanarya”?

    I appreciate it -Latia

    http://yahoo.com

    February 10, 2013 at 5:21 pm

  4. thank you sir , i am new to MVC Development .i learned a lot from your 3 posts

    excellent , Great job sir
    Raja Nandam

    rajasqlnotes

    June 23, 2013 at 12:00 am


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 68 other followers

%d bloggers like this: