asp.net-mvc – 如何将HTML5表单操作链接到ASP.NET MVC 4中的Controller ActionResult方法

我有一个基本的表单,我想通过调用视图的关联Controller类中的ActionResult方法来处理窗体中的按钮.以下是以下格式的HTML5代码
<h2>Welcome</h2>

<div>

    <h3>Login</h3>

    <form method="post" action= <!-- what goes here --> >
        Username: <input type="text" name="username" /> <br />
        Password: <input type="text" name="password" /> <br />
        <input type="submit" value="Login">
        <input type="submit" value="Create Account"/>
    </form>

</div>

<!-- more code ... -->

相应的控制器代码如下:

[HttpPost]
public ActionResult MyAction(string input,FormCollection collection)
{
    switch (input)
    {
        case "Login":
            // do some stuff...
            break;
        case "Create Account"
            // do some other stuff...
            break;
    }

    return View();
}

解决方法

你使用HTML助手并拥有
@using(Html.BeginForm())
    {
        Username: <input type="text" name="username" /> <br />
        Password: <input type="text" name="password" /> <br />
        <input type="submit" value="Login">
        <input type="submit" value="Create Account"/>
    }

或使用Url帮助器

<form method="post" action="@Url.Action("MyAction","MyController")" >

Html.BeginForm有几个(13)覆盖,您可以在其中指定更多信息,例如上传文件正在使用时的正常使用:

@using(Html.BeginForm("myaction","mycontroller",FormMethod.Post,new {enctype = "multipart/form-data"}))
{
    < ... >
}

如果不指定任何参数,Html.BeginForm()将创建一个指向当前控制器和当前操作的POST表单.举个例子,假设你有一个叫做帖子的控制器和一个叫做“删除”的动作

public ActionResult Delete(int id)
{
   var model = db.GetPostById(id);
   return View(model);
}

[HttpPost]
public ActionResult Delete(int id)
{
    var model = db.GetPostById(id);
    if(model != null) 
        db.DeletePost(id);

    return RedirectToView("Index");
}

你的html页面将是这样的:

<h2>Are you sure you want to delete?</h2>
<p>The Post named <strong>@Model.Title</strong> will be deleted.</p>

@using(Html.BeginForm())
{
    <input type="submit" class="btn btn-danger" value="Delete Post"/>
    <text>or</text>
    @Url.ActionLink("go to list","Index")
}

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....