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.
Rendering a Partial View You can render the partial view in the parent view using the HTML helper methods: @html. Partial() , @html. RenderPartial() , and @html. RenderAction() .
In order to add Partial View, you will need to Right Click inside the Controller class and click on the Add View option in order to create a View for the Controller.
RenderPartial(HtmlHelper, String) Renders the specified partial view by using the specified HTML helper. RenderPartial(HtmlHelper, String, Object) Renders the specified partial view, passing it a copy of the current ViewDataDictionary object, but with the Model property set to the specified model.
To return a Partial view from the controller action method, we can write return type as PartialViewResult and return using PartialView method.
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.
You could render the page before hand, but within a hidden div, or you could use AJAX to load it after the click.
<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();
});
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/');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With