【问题标题】:ASP.NET MVC - Multiple Buttons on a FormASP.NET MVC - 窗体上的多个按钮
【发布时间】:2009-04-04 02:47:20
【问题描述】:

我想在这个表单上有多个按钮作为图像:

<% Html.BeginForm("Create", "Foos", FormMethod.Post); %>

    <!-- html form elements -->
    <%=Html.SubmitImage("Button", "save-button.gif", new { alt = "Save" })%>

<% Html.EndForm(); %>

我正在阅读有关 Html.ActionImage 的信息,但我在 Microsoft.Web.Mvc 中没有看到它,我猜它已被删除,还有其他添加按钮的方法吗?

我想要一个表单上的保存、删除、发布、取消等按钮,作为图像,最好每个都在控制器中调用自己的操作。

【问题讨论】:

  • 您希望取消是文本链接、html 输入按钮还是图片链接?
  • 一个类似于提交按钮的图像。
  • 你最后做了什么?这是几个月前的事了

标签: asp.net-mvc


【解决方案1】:

你可以使用好的ole html:

<input type="button" name="CancelButton" id="CancelButton" value="Cancel" />

<button name="CancelButton" id="CancelButton">Cancel</button>

或其中一位助手

<%= Html.Button("CancelButton", "Cancel", "MyJavascriptFunction()") %>

在任何情况下,除非您只想使用取消链接,否则您可能需要编写一些 javascript。

这里有一点关于助手的blog entry

【讨论】:

  • 感谢您的回复,但不接受使用 javascript 进行导航。您仍然有一些很好的答案,所以 +1。
【解决方案2】:

当然,一个选择是为每个按钮设置单独的表单。如果没有 Javascript 或格式错误的 HTML,这通常是不可能的或容易的。这很容易让您将每个请求发送到不同的操作方法。

这是我为多个图像提交按钮提出的解决方案。我对此不是特别满意,但它可以工作,并且如果框架中内置了替代方案,以后可以轻松重构。

在您的 HTML 中:

<%= Html.SubmitImage("Dog", "~/images/dog.jpg")%>
<%= Html.SubmitImage("Cat", "~/images/cat.jpg")%>

在表单的控制器操作方法中:

(这是一个动作方法。由你决定如何实现每个按钮)

    public ActionResult Index(FormCollection form)
    {
        // get the name of the button that was clicked (sent via either Dog.x or Cat.x since its an image button)
        var buttonName = form.GetSubmitButtonName();

        if (buttonName == "Remove" || buttonName == "Skip")
        {
           Remove(form);
        }
        else if (buttonName == "Add")
        {
           Add(form);
        }
     }

扩展方法:

(这会找到一个名为 Remove.x 或 Skip.x 或 Add.x 的表单参数并去掉 .x 部分)

public static class FormCollectionExtensions
{
    public static string GetSubmitButtonName(this FormCollection formCollection)
    {
        var button = formCollection.Keys.OfType<string>().Where(x => x.EndsWith(".x")).SingleOrDefault();

        // we got something like AddToCart.x
        if (button != null)
        {
            return button.Substring(0, button.Length - 2);
        }

        throw new ApplicationException("No image button found");
    }
}

注意:一种替代方法是使用 CSS 将背景图像放在常规 Html.SubmitButton 按钮类型(常规 HTML 按钮而不是 HTML 图像按钮)上,但由于不同不同浏览器的行为方式 (see this question)。

【讨论】:

    猜你喜欢
    • 2016-04-16
    • 1970-01-01
    • 2016-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-08
    相关资源
    最近更新 更多