jQuery 如何在单击 HTML 按钮时呈现部分页面?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7352444/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I render a partial page on click a HTML Button?
提问by OBL
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?
我是 MVC3.0 的新手,必须使用 jquery。我想知道有人可以帮助我如何在单击 HTML 按钮时呈现部分视图页面?
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.
我知道这真的很简单,该按钮可以称为“email to”,它将用于名为“emailForm”的 partialView。但我需要一些帮助。
回答by smdrager
You could render the page before hand, but within a hidden div, or you could use AJAX to load it after the click.
您可以事先渲染页面,但在隐藏的 div 中,或者您可以在单击后使用 AJAX 加载它。
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
用 Ajax 加载
To do this you'd create an ActionResult in a controller which renders the partial.
为此,您需要在呈现部分的控制器中创建一个 ActionResult。
<div id="partial"></div>
<button type="button" id="load-partial" />
and a script
和一个脚本
$('#load-partial').click(function(){
$('#partial').load('/TheController/TheAction/');
});
回答by DMac the Destroyer
I'd say @smdrager's response is the desired route, if possible. If you needto get html from an ajax request, however, there are manyways to do it... here's an example of one :)
如果可能的话,我会说@smdrager 的回应是所需的路线。但是,如果您需要从 ajax 请求中获取 html,则有很多方法可以做到……这是一个示例:)
In your template, you'd have a button or link, and a div container for your content:
在您的模板中,您将有一个按钮或链接,以及一个用于内容的 div 容器:
<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:
您需要一些快速的 javascript 来连接客户端功能:
<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.
确保传入 javascript$.get
调用的 url指向返回部分的操作。
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.
这是一个非常基本的实现,如果您的情况变得更复杂(异常处理、参数传递等),它很容易变得更复杂,但是当我需要一个简单的 ajax 请求来触发时,一般布局对我有用。