如何在MVC 4中触发按钮单击

我是MVC的新手,我正在为我的应用创建一个注册表单,但我的按钮点击不正常工作当前代码未在下面给出

视图

Sign Up
@Html.Label("User Name") @Html.TextBoxFor(account => account.Username)
@Html.Label("Email") @Html.TextBoxFor(account => account.Email)
@Html.Label("Password") @Html.TextBoxFor(account => account.Password)
@Html.Label("Confirm Password") @Html.Password("txtPassword")

模型

 public class Account { public string Username { get; set; } public string Email { get; set; } public string Password { get; set; } } 

控制器(未完全完成)

  public class AccountController : Controller { // // GET: /Account/ public ActionResult Index() { return View(); } // GET: /Account/SignUp public ActionResult SignUp() { return View(); } [HttpPost] public ActionResult SignUp(string userName,string email,string password) { Account createAccount = new Account(); createAccount.Username = userName; createAccount.Email = email; createAccount.Password = password; return View("Index"); } } 

如何定义点击事件在这里我尝试了httppost,但它不起作用我知道我的代码不正确请指出这里的错误是什么

ASP.NET MVC不适用于ASP经典之类的事件; 没有“按钮点击事件”。 您的控制器方法对应于发送到服务器的请求。

相反,您需要在代码中包装该表单,如下所示:

 @using (Html.BeginForm("SignUp", "Account", FormMethod.Post)) {   } 

这将设置一个表单,然后您的提交输入将触发POST,这将触发您的SignUp()方法,假设您的路由已正确设置(默认值应该有效)。

根据@anaximander的回答,你的注册动作看起来应该更像

  [HttpPost] public ActionResult SignUp(Account account) { if(ModelState.IsValid){ //do something with account return RedirectToAction("Index"); } return View("SignUp"); } 

你可以尝试这个代码

 @using (Html.BeginForm("SignUp", "Account", FormMethod.Post)){
Sign Up
@Html.Label("User Name") @Html.TextBoxFor(account => account.Username)
@Html.Label("Email") @Html.TextBoxFor(account => account.Email)
@Html.Label("Password") @Html.TextBoxFor(account => account.Password)
@Html.Label("Confirm Password") @Html.Password("txtPassword")
}

MVC不做事件。 只需在页面上放置一个表单并提交按钮,使用HttpPost属性修饰的方法就会处理该请求。

您可能希望阅读有关如何创建视图,表单和控制器的教程。