Search code examples
jqueryasp.net-mvc-3renderpartial

How can I render a partial page on click a HTML Button?


I am new to MVC3.0 and have to use jquery. I as wondering some one can help with how can I render a partial view page on clicking a HTML Button?

I know it is really easy, the button could be called "email to", which will take use to a partialView called "emailForm". But I need some help.


Solution

  • I'd say @smdrager's response is the desired route, if possible. If you need to get html from an ajax request, however, there are many ways to do it... here's an example of one :)

    In your template, you'd have a button or link, and a div container for your content:

    <a href="javascript:void(0)" id="emailTo">email to</a>
    <div id="emailToContent"></div>
    

    You'll need some quick javascript to wire up the client-side functionality:

    <script type="text/javascript">
      $("#emailTo").click(function(){
        $.get("<url to partial>", function(data){$("#emailToContent").html(data);}
      });
    </script>
    

    Then, in your controller, you need an action that returns your partial:

    public ActionResult EmailTo()
    {
      ...
      return PartialView("some partial")
    }
    

    Make sure the url passed into the javascript $.get call is pointed to the action that returns your partial.

    This is a very basic implementation, which could easily get more complicated if your situation gets more complicated (exception handling, parameter passing, etc), but the general layout works for me when I need a simple ajax request to fire off.