ASP.NET MVC 4 で HTML5 フォームアクションをコントローラーの ActionResult メソッドにリンクする方法 質問する

ASP.NET MVC 4 で HTML5 フォームアクションをコントローラーの ActionResult メソッドにリンクする方法 質問する

基本的なフォームがあり、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();
}

ベストアンサー1

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現在のコントローラと現在のアクションを指します例えば、というコントローラ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")
}

おすすめ記事