如果你想生成完整的代码,你会错误地返回一个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("");
}
我编辑了最后一个答案 - 经过一些更改 - 似乎正常工作。 –
如何在HtmlHelper中做一个'response.Write'非常好的见解。谢谢!!希望我可以再次投票。 –