本文介绍了MVC Html.ActionButton的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有人写的吗?我希望它像一个链接,但看起来像一个按钮。一个按钮的表格不会做它,我不想任何职务。

Has anyone written one? I want it to behave like a link but look like a button. A form with a single button wont do it has I don't want any POST.

推荐答案

要做到这一点最简单的方法是有一个小表格 标签方法=获取,其中放置一个提交按钮:

The easiest way to do it is to have a small form tag with method="get", in which you place a submit button:

<form method="get" action="/myController/myAction/">
    <input type="submit" value="button text goes here" />
</form>

您当然可以写一个非常简单的扩展方法,它采用按钮文本和 RouteValueDictionary (或匿名类型与routevalues​​),并构建形式,所以你赢了'T不得不到处重新做。

You can of course write a very simple extension method that takes the button text and a RouteValueDictionary (or an anonymous type with the routevalues) and builds the form so you won't have to re-do it everywhere.

修改:为响应cdmckay的回答,下面是一个使用,而不是一个普通的<$ c中的 TagBuilder 类替代code $ C>的StringBuilder 来构建形式,多为清晰:

EDIT: In response to cdmckay's answer, here's an alternative code that uses the TagBuilder class instead of a regular StringBuilder to build the form, mostly for clarity:

using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Web.Routing;

namespace MvcApplication1
{
    public static class HtmlExtensions
    {
    	public static string ActionButton(this HtmlHelper helper, string value, 
                              string action, string controller, object routeValues)
    	{
    		var a = (new UrlHelper(helper.ViewContext.RequestContext))
    					.Action(action, controller, routeValues);

    		var form = new TagBuilder("form");
    		form.Attributes.Add("method", "get");
    		form.Attributes.Add("action", a);

    		var input = new TagBuilder("input");
    		input.Attributes.Add("type", "submit");
    		input.Attributes.Add("value", value);

    		form.InnerHtml = input.ToString(TagRenderMode.SelfClosing);

    		return form.ToString(TagRenderMode.Normal);
    	}
    }
}

此外,相对于cdmckay的code,这个人会实际编译)据我所知,可能有相当多的开销在这个code,但我希望您将不再需要在每一页上运行了很多次。在你做的情况下,有可能是一堆的优化,你可以做的。

Also, as opposed to cdmckay's code, this one will actually compile ;) I am aware that there might be quite a lot of overhead in this code, but I am expecting that you won't need to run it a lot of times on each page. In case you do, there is probably a bunch of optimizations that you could do.

这篇关于MVC Html.ActionButton的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 21:27