asp.net-mvc 如何使用按钮(非提交)单击事件来调用控制器上的方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19381302/
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 do I use a Button(Non Submit) Click Event to call a method on my Controller?
提问by Refracted Paladin
I feel ridiculous asking this question but here goes, I am trying to make a very simple ASP.NET MVC 5 app. My first of it's kind. I want to have a button that when clicked does something but doesn't change the user's view or at most returns a "Email has been submitted" message.
问这个问题我觉得很可笑,但在这里,我正在尝试制作一个非常简单的 ASP.NET MVC 5 应用程序。我的第一个善良。我想要一个按钮,当点击它时会执行某些操作但不会更改用户的视图或最多返回“电子邮件已提交”消息。
My problem is I can't figure out how to wire a button to an "event" or "action" that doesn't change the view(i.e. using @Html.ActionLink()) or is a Submit button. Every example I find is also of a Submit button.
我的问题是我不知道如何将按钮连接到不改变视图(即使用@Html.ActionLink())或提交按钮的“事件”或“动作” 。我找到的每个示例也是提交按钮。
Thanks for any help.
谢谢你的帮助。
EDIT
编辑
This is still not working for me. I'll post my code below. My effort is based on what was said here and on the linked post. Also, FYI, I can make it work with `@Html.ActionLink("link text", "actionname") but that appears as a link and I am trying to use a "Button".
这仍然对我不起作用。我将在下面发布我的代码。我的努力基于此处和链接帖子中所说的内容。另外,仅供参考,我可以使用`@Html.ActionLink("link text", "actionname") 使其工作,但它显示为链接,我正在尝试使用“按钮”。
Index.cshtml
索引.cshtml
@{
ViewBag.Title = "Home Page";
}
<div class="hero-unit">
<h3>Marketing & Communications Project Request Form</h3>
<p>User: <strong>@Context.User.Identity.Name</strong></p>
</div>
<div class="row">
<div class="span4">
@Html.ActionLink("Send Email", "SendEmail") @*this line works*@
<input id="SendEmail" class="btn" type="button" value="SendEmail" /> @*this line does not
</div>
</div>
<script type="text\javascript">
$(function(){
var url = '@Url.Action("SendEmail", "HomeController")';
$("input#SendEmail").on('click', function() {
$.ajax({
url: url
})
});
});
</script>
HomeController
家庭控制器
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
public ActionResult SendEmail()
{
//Code to create and send email here
return View("Index");
}
}
回答by Jason Evans
OK, say you have the following button, written in HTML:
好的,假设您有以下按钮,用 HTML 编写:
<input type="button" id="MyButton" value="Click Me />
You can use jQuery to hook up to the clickevent:
您可以使用 jQuery 来连接click事件:
$(function(){
$("input#MyButton").on('click', function(){
// Do what you want.
});
});
If you use a HTML helper, such as HTML.TextBoxFor(), as long as you know the id of the inputthat is generated, you can use the same jQuery code to hook up the clickevent.
如果您使用 HTML 助手,例如HTML.TextBoxFor(),只要您知道input生成的 id ,您就可以使用相同的 jQuery 代码来连接click事件。
EDIT:
编辑:
You can place that jQuery code either in the view e.g.
您可以将该 jQuery 代码放置在视图中,例如
<script type="text/javascript">
$(function(){
$("input#MyButton").on('click', function(){
// Do what you want.
});
});
</script>
Usually you find script code placed near the bottom of the view, but you can place it anywhere you like really.
通常您会发现脚本代码放置在视图底部附近,但您可以将其放置在您真正喜欢的任何位置。
Or you could place that jQuery in a separate JavaScript (*.js) file. Just make sure you add the following to the <head>section in _Layout.cshtml:
或者,您可以将该 jQuery 放在单独的 JavaScript (*.js) 文件中。只需确保将以下内容添加到 中的<head>部分_Layout.cshtml:
<script type='text/javascript' src='@Url.Content("~Scripts/YourFile.js")' ></script>
<script type='text/javascript' src='@Url.Content("~Scripts/YourFile.js")' ></script>
_Layout.cshtmlis a master layout file that is used across your project (assuming you have picked one of the usual ASP.NET MVC project templates in Visual Studio).
_Layout.cshtml是在您的项目中使用的主布局文件(假设您在 Visual Studio 中选择了常用的 ASP.NET MVC 项目模板之一)。
EDIT:
编辑:
Regards the jQuery reference, in _Layout.cshtmlyou can add this, if jQuery is not already referenced:
关于 jQuery 参考,_Layout.cshtml如果尚未引用jQuery,您可以添加它:
<script type='text/javascript' src='@Url.Content("~Scripts/jquery.version.js")' ></script>
<script type='text/javascript' src='@Url.Content("~Scripts/jquery.version.js")' ></script>
Just replace the filename for the correct one you have. Now, things get interesting if your MVC app uses bundling. That's a bit out of my knowledge bank, so might be better to look at other SO questions that talk about CSS/JavaScript bundling in MVC apps.
只需将文件名替换为您拥有的正确文件名。现在,如果您的 MVC 应用程序使用捆绑,事情就会变得有趣。这有点超出我的知识库,所以最好看看其他关于 MVC 应用程序中的 CSS/JavaScript 捆绑的 SO 问题。
回答by Murali Murugesan
You could simply achieve with this below sample code using jQuery ajax(post) call
您可以使用 jQuery ajax(post) 调用通过以下示例代码简单地实现
<a id="btn-send-mail">SendEmail</a>
JS
JS
$(document).ready(function(){
$('#btn-send-mail').click(function(e){
e.preventDefault();
var emailData={};
emailData.toMail='[email protected]';
$.post('/Mail/Send/',{data:emailData}, function(result){
if(result.status==true){
alert('Email submitted successfully');
}});//end of post
});//end of click
});//end of ready
Controller code
控制器代码
public class MailController
{
[HttpPost]
public JsonResult Send(Email obj)
{
//Code for sending email
return Json(new {status=true});
}
}
回答by hjgraca
If you don't want to use normal jquery call you can take advantage of Razor @Ajax.ActionLink.
如果您不想使用普通的 jquery 调用,您可以利用 Razor @Ajax.ActionLink。
You just set up the link like a normal Html.ActionLink and then create a controller action that sends your email, since this call is asynchronous it wont refresh the page.
您只需像普通的 Html.ActionLink 一样设置链接,然后创建一个发送电子邮件的控制器操作,因为此调用是异步的,因此不会刷新页面。
@Ajax.ActionLink("Send Email", // <-- Text to display
"SendEmail", // <-- Action Method Name
new AjaxOptions
{
UpdateTargetId="", // <-- Used if you want to update up, DOM element ID to update
HttpMethod = "GET" // <-- HTTP method
})
I would recomend doing the jquery way but here is an exampleusing Ajax.ActionLink
我会推荐使用 jquery 的方式,但这里有一个使用 Ajax.ActionLink的例子

