Skip to content

Instantly share code, notes, and snippets.

@devlights
Created December 1, 2012 11:05
Show Gist options
  • Save devlights/4181534 to your computer and use it in GitHub Desktop.
Save devlights/4181534 to your computer and use it in GitHub Desktop.
[ASP.NET MVC] Select action-method in the same form.action. (ActionMethodSelectorAttribute)
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;
}
}
}
@{
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>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment