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

2024-02-26

我有一个基本表单,我想通过调用来处理表单内的按钮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 ... -->

相应的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();
}

您使用 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"/>
    }

或使用 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形成那个指向你当前的控制器和当前的操作。举个例子,假设你有一个名为Posts和一个名为的动作Delete

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")
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将 HTML5 表单操作链接到 ASP.NET MVC 4 中的控制器 ActionResult 方法 的相关文章

随机推荐