Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
633 views
in Technique[技术] by (71.8m points)

asp.net mvc - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

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.

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);
        }
    }
}

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...