如果你想生成完整的代碼,你會錯誤地返回一個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'非常好的見解。謝謝!!希望我可以再次投票。 –