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

dtg*_*dtg 32 asp.net-mvc html5 razor asp.net-mvc-4

我有一个基本的表单,我想通过调用ActionResultView的关联Controller类中的方法来处理表单内的按钮.以下是表单的以下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 ... -->
Run Code Online (Sandbox Code Playgroud)

相应的Controller代码如下:

[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();
}
Run Code Online (Sandbox Code Playgroud)

bal*_*dre 72

你使用HTML Helper并拥有

    @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"/>
    }
Run Code Online (Sandbox Code Playgroud)

或使用Url助手

<form method="post" action="@Url.Action("MyAction", "MyController")" >
Run Code Online (Sandbox Code Playgroud)

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

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

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

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");
}
Run Code Online (Sandbox Code Playgroud)

你的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")
}
Run Code Online (Sandbox Code Playgroud)