如果您想生成完整的代码,那么让它返回MvcForm 是错误的。您希望它返回一个 MvcHtmlString 并在该方法中构造 HTML。这样您就可以将其用作:
@Html.DeleteButton( "Delete", "Boodschap", new { id = item.BoodschapID } );
直接生成 HTML(注意:未经测试,您可能需要合适的空值检查等)
public static MvcHtmlString DeleteButton( this HtmlHelper helper, string name,
string actionName, object htmlAttributes )
{
return DeleteButton( helper, name, actionName, null, null, htmlAttributes );
}
public static MvcHtmlString DeleteButton( this HtmlHelper helper, string name,
string actionName, string controllerName, object routeValues,
object htmlAttributes )
{
var buttonBuilder = new TagBuilder("button");
buttonBuilder.SetInnerText( name );
var formBuilder = new TagBuilder("form");
var urlHelper = new UrlHelper( helper.ViewContext.RequestContext );
formBuilder.Attributes.Add( "action", urlHelper.Action(
actionName, controllerName, routeValues ) )
formBuilder.Attributes.Add( "method", FormMethod.Post );
formBuilder.MergeAttributes( new RouteValueDictionary( htmlAttributes ) );
formBuilder.InnerHtml = buttonBuilder.ToString();
return new MvcHtmlString( formBuilder.ToString() );
}
另一种方法是重用表单助手和 Response.Write,但让该方法返回一个(空)字符串,可能类似于:
public static MvcHtmlString DeleteButton(this HtmlHelper helper, string name, string actionName, object routeValues)
{
return DeleteButton(helper, name, actionName, null, routeValues, null);
}
public static MvcHtmlString DeleteButton(this HtmlHelper helper, string name, string actionName, string controllerName, object routeValues, object htmlAttributes)
{
using (helper.BeginForm(actionName, controllerName, routeValues, FormMethod.Post, htmlAttributes))
{
var response = helper.ViewContext.HttpContext.Response;
var builder = new TagBuilder("button");
builder.SetInnerText(name);
response.Write(builder.ToString(TagRenderMode.Normal));
}
return MvcHtmlString.Create("");
}