OBL
OBL

Reputation: 1357

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.

Upvotes: 8

Views: 41198

Answers (2)

smdrager
smdrager

Reputation: 7417

You could render the page before hand, but within a hidden div, or you could use AJAX to load it after the click.

Hidden Div

<div style="display:none;" id="partial">
    @Html.Partial("SomePartial")
</div>

<button type="button" id="show-partial" />

and a script

$('#show-partial').click(function(){
    $('#partial').show();
});

Load with Ajax

To do this you'd create an ActionResult in a controller which renders the partial.

<div id="partial"></div>

<button type="button" id="load-partial" />

and a script

$('#load-partial').click(function(){
    $('#partial').load('/TheController/TheAction/');
});

Upvotes: 14

DMac the Destroyer
DMac the Destroyer

Reputation: 5290

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.

Upvotes: 14

Related Questions