Skip to main content

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);
     }

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. 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
  10. 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
  11. helpful. thanks!

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

    ReplyDelete

Post a Comment

Popular posts from this blog

Asp.net mvc razor render partial view using ajax helper

This is the extension to my blog in which I demonstrated rendering of the partial view using jquery Ajax . I want to demonstrate here yet another way by which partial view can be rendered without page refresh. Here is the implementation. Step 1: I will again be using DisplayData class in my demo. Here is it. public class DisplayData { public int ID { get; set; } public DisplayData(int ID) { this.ID = ID; } } Step 2: Create a PartialDemo page @model IEnumerable<MvcApplication5.Models.DisplayData> @{ ViewBag.Title = "PartialDemo"; } @Ajax.ActionLink("Click 1", "PartialDemo", "PartialDemo", new {Data= "1" }, new AjaxOptions { UpdateTargetId = "rsvpmsg" }) @Ajax.ActionLink("Click 2", "PartialDemo", "PartialDemo", new {Data= "2" }, new AjaxOptions { UpdateTargetId = "rsvpmsg" }) <div id="rsvpms...

Entity Framework many to many relationship.

In this post I will be demonstrating how you can create many to many relationship between classes by using EF code first approach with DataAnnotation attributes. You can use the EF fluent API as well for many to many configuration which I have not covered here. I will be using the classes post and tag in my model which has many to many relationship between them i.e a single post can have many tags and a single tag can have many posts. To get started with many to many configuration between the post and the tag you have to create the classes first. The EF will automatically create the third table when the application will execute, so you will not be creating the third table manually in the model. Let's get started with the code. public class Post { public long PostID { get; set; } [Required] [MaxLength(255)] public string Title { get; set; } [Required] [MaxLength(4000)] [DataType(DataType.MultilineText)] public string Question { g...