首先,我创建一个 ModelBinder 来处理传入的请求。
我必须做出限制。输入/按钮元素 id 和名称必须是“cmd”前缀。
public class CommandModelBinder<T> : IModelBinder
{
public CommandModelBinder()
{
if (!typeof(T).IsEnum)
{
throw new ArgumentException("T must be an enumerated type");
}
}
public object BindModel(System.Web.Mvc.ControllerContext controllerContext, ModelBindingContext bindingContext)
{
string commandText = controllerContext.HttpContext.Request.Form.AllKeys.Single(key => key.StartsWith("cmd"));
return Enum.Parse(typeof (T), commandText.Substring(3));
}
}
当然可以通过App_Start的web.config进行更改或配置。
我接下来要做的是一个 HtmlHelper 扩展来生成必要的 HTML 标记:
public static MvcHtmlString CommandButton<T>(this HtmlHelper helper, string text, T command)
{
if (!command.GetType().IsEnum) throw new ArgumentException("T must be an enumerated type");
string identifier = "cmd" + command;
TagBuilder tagBuilder = new TagBuilder("input");
tagBuilder.Attributes["id"] = identifier;
tagBuilder.Attributes["name"] = identifier;
tagBuilder.Attributes["value"] = text;
tagBuilder.Attributes["type"] = "submit";
return new MvcHtmlString(tagBuilder.ToString());
}
它仍然是一个技术演示,因此 html 属性和其他超级重载等待您自己开发。
现在我们必须进行一些枚举来尝试我们的代码。它们可以是通用的,也可以是特定于控制器的:
public enum IndexCommands
{
Save,
Cancel
}
public enum YesNo
{
Yes,
No
}
现在将枚举与活页夹配对。我在 App_Start 文件夹中的不同文件中执行此操作。 ModelBinder配置。
ModelBinders.Binders.Add(typeof(IndexCommands), new CommandModelBinder<IndexCommands>());
ModelBinders.Binders.Add(typeof(YesNo), new CommandModelBinder<YesNo>());
现在,在我们设置完所有内容后,请执行操作来尝试代码。我保持简单:
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(IndexCommands command)
{
return View();
}
我的观点是这样的:
@using (Html.BeginForm())
{
@Html.CommandButton("Save", IndexCommands.Save)
@Html.CommandButton("Cancel", IndexCommands.Cancel)
}
希望这有助于保持您的代码清晰、类型安全且可读。