Nếu bạn muốn tạo mã đầy đủ, bạn sẽ sai về việc trả lại mã số MvcForm
. Bạn muốn có nó trả về một MvcHtmlString
và xây dựng HTML trong phương thức. Bằng cách đó bạn có thể sử dụng nó như:
@Html.DeleteButton("Delete", "Boodschap", new { id = item.BoodschapID });
Tạo mã HTML trực tiếp (lưu ý: chưa được kiểm tra, bạn có thể cần kiểm tra rỗng thích hợp vv)
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());
}
Một thay thế sẽ được tái sử dụng các hình thức giúp đỡ và Response.Write, nhưng có phương pháp trả về một (trống) chuỗi, có lẽ cái gì đó như:
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("");
}
Tôi đã chỉnh sửa câu trả lời cuối cùng - sau một số thay đổi - dường như hoạt động chính xác. –
Thông tin chi tiết rất hay về cách thực hiện 'phản hồi.Write' trong HtmlHelper. Cảm ơn!! Ước gì tôi có thể bỏ phiếu lại. –