devlights
12/1/2012 - 11:05 AM

[ASP.NET MVC] Select action-method in the same form.action. (ActionMethodSelectorAttribute)

[ASP.NET MVC] Select action-method in the same form.action. (ActionMethodSelectorAttribute)

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
<hr />
<h1>@ViewBag.Message [@(Request["txt1"])]</h1>
<hr />
@using(Html.BeginForm("InsertAndDelete", "Home")) {

  <fieldset>
    <legend>Sample Form</legend>
    <input type="text" name="txt1" value="@(Request["txt1"] ?? "Hello World")" />
    <div>
      <input type="submit" name="Insert" value="登録" />
      <input type="submit" name="Delete" value="削除" />
    </div>
  </fieldset>

}
namespace MvcApplication2.Controllers
{
  using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Web;
  using System.Web.Mvc;

  public class HomeController : Controller
  {
    public ActionResult Index()
    {
      ViewBag.Message = "Indexアクションが呼ばれました";
      return View();
    }

    [HttpPost]
    [Button(ButtonName="Insert")]
    [ActionName("InsertAndDelete")]
    public ActionResult Insert()
    {
      ViewBag.Message = "Insertアクションが呼ばれました";
      return View("Index");
    }

    [HttpPost]
    [Button(ButtonName="Delete")]
    [ActionName("InsertAndDelete")]
    public ActionResult Delete()
    {
      ViewBag.Message = "Deleteアクションが呼ばれました";
      return View("Index");
    }
  }

  public class ButtonAttribute : ActionMethodSelectorAttribute
  {
    public string ButtonName { get; set; }

    public override bool IsValidForRequest(ControllerContext context, System.Reflection.MethodInfo methodInfo)
    {
      return context.Controller.ValueProvider.GetValue(ButtonName) != null;
    }
  }
}