public static MvcForm BeginFormAnchor(this HtmlHelper htmlHelper, string actionName, string controllerName, object routeValues, FormMethod method, object htmlAttributes, string hashTag)
{
var formAction = UrlHelper.GenerateUrl(null, actionName, controllerName, htmlHelper.ViewContext.HttpContext.Request.Url.Scheme, null, hashTag, ConvertToRouteValueDictionary(routeValues), htmlHelper.RouteCollection, htmlHelper.ViewContext.RequestContext, true);
var builder = new TagBuilder("form");
builder.MergeAttribute("action", formAction);
builder.MergeAttribute("method", method.ToString(), true);
foreach (KeyValuePair<string, string> attribute in ConvertToDictionaryStringString(htmlAttributes))
{
builder.MergeAttribute(attribute.Key, attribute.Value);
}
htmlHelper.ViewContext.Writer.Write(builder.ToString(TagRenderMode.StartTag));
return new MvcForm(htmlHelper.ViewContext);
}
private static Dictionary<string, string> ConvertToDictionaryStringString(object obj)
{
return obj.GetType().GetProperties().ToDictionary(o => o.Name, o => o.GetValue(obj, null).ToString());
}
private static RouteValueDictionary ConvertToRouteValueDictionary(object obj)
{
RouteValueDictionary rvd = new RouteValueDictionary();
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(obj);
foreach (PropertyDescriptor prop in props)
{
rvd.Add(prop.Name, prop.GetValue(obj));
}
return rvd;
}
私はそれを次のような形で呼んでいます:
@using (Html.BeginFormAnchor("Action", "Controller", new { id = Model.ID }, FormMethod.Post, new { @id = "formID" }, "anchorName"))