Thursday, 14 April 2011

Asp.net mvc razor render partial view using jquery Ajax

I will going to demonstrate how we can render PartialViews using Jquery Ajax. I will be clicking an a href link ,then I will be calling the controller through jquery Ajax which will fill the partialview for a really nice user experience.

Step 1:

First of all we will be creating an DisplayData class for the use for this example in the model.
    public class DisplayData
    {
       public int ID { get; set; }
       public DisplayData(int ID)
       {
              this.ID = ID;
       }
    }


Step 2:

We will create a Clicks page and write the following code on it. Specially note empty here which will going to empty and then fill partialview with new records.
     $(document).ready(function () {
        $('.msg').click(function () {
            var id = this.id;
            $.ajax({
                url: "/Category/Display",
                data: { data: id },
                success: function (mydata) {
                    $("#link").empty().append(mydata);
                },
                type: "POST"
            });
            return false;
        });
    }); 


<a class="msg" href="#" id="1">Click Me</a>
<a class="msg" href="#" id="2">AND Click Me</a>
<div id="link">
</div>

Step 3:

Create a User Control ClicksUC for partial rendering
foreach(var items in Model)
{  
    @items.ID  
}

Step 4:

And Finally Create an action methods inside the Category controller for calling the view and then rendering the partialview.

     public ActionResult Clicks()
     {
         return View();
     }
          
     public ActionResult Display(int data)
     {
         List<DisplayData> Display = new List<DisplayData>();
         if (data == 1)
         {
           Display.Add(new DisplayData(3));
           Display.Add(new DisplayData(4));
         }
         else
         {
           Display.Add(new DisplayData(1));
           Display.Add(new DisplayData(2));
         }
          
         return PartialView("ClicksUC", Display);
     }

13 comments:

  1. I have tried this and works great on my development environment under localhost. Once I move it to a server with a domain name, the ajax calls fail.

    Any ideas why?

    ReplyDelete
  2. There is absolutely no reason for it not to work in the domain environment. OK if it is the problem with the Ajax call then check it with fiddler or firebug.These are great tools and I am sure using these you would get to the solution to the problem.

    ReplyDelete
  3. works........ gr8

    ReplyDelete
  4. I have the same problem that works great on my development environment under localhost. Once I move it to a web server with a domain name, nothing will happen. How do you solve the problem. thanks

    ReplyDelete
  5. try fiddler or firebug to get to the root of the problem. I think specifying /Category/Display in global.asax will solve this problem.

    ReplyDelete
  6. This is actually really clever, one of the few guides I've managed to find about this. It works fine for me although I'm in the middle of trying to pass a populated model, I'll let you know if I can figure it out...

    ReplyDelete
  7. nice. i was looking for such a simple solution instead of using jquery tempate or knockout.js etc.

    ReplyDelete
  8. Good one, this help me a lot.

    ReplyDelete
  9. This... saved... my... bacon!

    Thank you!

    ReplyDelete
  10. The one who are facing an issue of not working this code on environments other than dev environment. Its because here the url is hard-coded in url: attribute, whereas you should try with @Url.Action.. A nice article overall. Thanks for sharing

    ReplyDelete
  11. hellow everyone this is sohaib ameen here and I am using Jquery with ajax in mvc3 application. I am having a button control on "FindStudents.cshmtl" with name "AddStudents". On button click my application is supposed to get student form with the help of a partial view which must replace "findstudents.cshtml" page contents.

    I have displayed the contents through ajax call in jquery but it is also showing view's own content either. how to replace them ..
    here is my Jquery code as well..


    $("#render").click(function () {

    alert("button Clikced");
    $.ajax({
    url: "AddStudentsPartial",
    type: 'GET',
    cache: false,
    success: function (result) {
    alert(result);
    $('#partial').html(result);
    }
    });
    });

    ReplyDelete
  12. helpful. thanks!

    ReplyDelete
  13. Can you please provide little more details like where to add what.. I am beginner in MVC/ASP.Net

    ReplyDelete