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

Asp.net mvc DataAnnotation ValidateAttribute two properties comparison.

Using Datannotion is great but there are scenarious in which the current attributes compare, range etc becomes inadequate especially for the comparisions. So we create here our own custom validation using ValidationAttribute class which is the base class for all the annotation attributes. So by deriving from it and overriding the Isvalid method we can create our custom attribute for the model. So here is the scenario in which I will be validating the Username against the password which should not be equal. Compare attribute cannot be used in this scenario so I have created a custom attribute for that. Here is the model with the attribute. User View Model [CompareUserPass("UserName", "Password", ErrorMessage = "UserName and password cannot be equal")] public class UserView { [Required(ErrorMessage = "UserName Required")] public string UserName { get; set; } [Required(