寻找一个接受MVC3中的类属性的Html.SubmitButton助手

Man*_*ona 13 asp.net-mvc

我想在MVC3中使用一个帮助程序来提交按钮.有这样的东西吗?如果没有,那么有谁知道我可以在哪里得到一些代码.我想要一个允许我传递类属性的.

arc*_*hil 19

写作并不简单

<input type="submit" class="myclassname"/>

在MVC中,没有像控件这样的东西,它们带有很多应用程序逻辑.事实上,这是可能的,但不推荐.我想说的是,Html助手只是让Html写得更舒服,并帮助你不要编写重复的代码.在您的特定情况下,我认为编写直接html比使用帮助程序更简单.但无论如何,如果你愿意,它包含在MVC期货图书馆中.调用方法SubmitButton


Mik*_*ail 13

只需使用以下代码添加到项目类:

using System.Text;

namespace System.Web.Mvc
{
public static class CustomHtmlHelper
{
    public static MvcHtmlString SubmitButton(this HtmlHelper helper, string buttonText, object htmlAttributes = null)
    {
        StringBuilder html = new StringBuilder();
        html.AppendFormat("<input type = 'submit' value = '{0}' ", buttonText);
        //{ class = btn btn-default, id = create-button }
        var attributes = helper.AttributeEncode(htmlAttributes);
        if (!string.IsNullOrEmpty(attributes))
        {
            attributes = attributes.Trim('{', '}');
            var attrValuePairs = attributes.Split(',');
            foreach (var attrValuePair in attrValuePairs)
            {
                var equalIndex = attrValuePair.IndexOf('=');
                var attrValue = attrValuePair.Split('=');
                html.AppendFormat("{0}='{1}' ", attrValuePair.Substring(0, equalIndex).Trim(), attrValuePair.Substring(equalIndex + 1).Trim());
            }
        }
        html.Append("/>");
        return new MvcHtmlString(html.ToString());
    }
}
}
Run Code Online (Sandbox Code Playgroud)

用法示例:

@Html.SubmitButton("Save", new { @class= "btn btn-default", id="create-button" })
Run Code Online (Sandbox Code Playgroud)


Saf*_*Ali 3

chk 这个链接它告诉您如何创建自定义帮助程序方法,并且没有内置的提交帮助程序...

http://stephenwalther.com/blog/archive/2009/03/03/chapter-6-understanding-html-helpers.aspx

它还包括一个非常基本的提交帮助方法,希望它有所帮助