In view, call to create the button
@Html.Button("Create", "user", -1)
the function
public static class HtmlExtensions
{
public static IHtmlString Button(this HtmlHelper htmlHelper, string buttonText, string controllerName, int id)
{
using (var db = new DA_Reporting_ServiceContext())
{
User user = db.Users.First(u => u.User_Login == htmlHelper.ViewContext.HttpContext.User.Identity.Name);
var button = new TagBuilder("input");
//button.SetInnerText(buttonText);
button.MergeAttribute("type", "submit");
button.MergeAttribute("value", buttonText);
if (!user.IsAuthorized(controllerName, id))
{
button.MergeAttribute("disabled", "disabled");
}
return new HtmlString(button.ToString());
}
}
public static IHtmlString PermitLink(this HtmlHelper htmlHelper, string linkText, string controllerName, string actionName, object routeValues)
{
bool hasPermission = false;
using (var db = new DA_Reporting_ServiceContext())
{
User user = db.Users.First(u => u.User_Login == htmlHelper.ViewContext.HttpContext.User.Identity.Name);
hasPermission = user.IsAuthorized(controllerName, int.Parse(routeValues.ToString().Split(',')[0].Split('=')[1])); // get the first parameter as the default id
}
if (hasPermission)
{
var link = new TagBuilder("a");
link.SetInnerText(linkText);
StringBuilder sb= new StringBuilder();
sb.AppendFormat(@"/{0}/{1}?",controllerName,actionName);
foreach (var item in ParseRouteValues(routeValues))
{
sb.Append(item.Key + "=" + item.Value+"&");
}
link.MergeAttribute("href", sb.ToString());
return new HtmlString(link.ToString());
}
return new HtmlString("");
}
public static IHtmlString Message(this HtmlHelper htmlHelper, TempDataDictionary tempData)
{
var label = new TagBuilder("label");
if (!String.IsNullOrEmpty((string)tempData["info"]))
{
label.SetInnerText(((string)tempData["info"]).Replace(System.Environment.NewLine,"
"));
label.AddCssClass("InfoMessage");
}
if (!String.IsNullOrEmpty((string)tempData["error"]))
{
label.SetInnerText(((string)tempData["error"]).Replace(Environment.NewLine,"
"));
label.AddCssClass("ErrorMessage");
}
if(label.InnerHtml.Length>0)
return new HtmlString("
"+label.ToString()+"
");
return new HtmlString(label.ToString());
}
private static Dictionary
ParseRouteValues(object _routeValues)
{
string values = _routeValues.ToString().Substring(1, _routeValues.ToString().Length - 2);
Dictionary pairs = new Dictionary();
foreach (var item in values.Split(','))
{
pairs.Add(item.Split('=')[0].Trim(), item.Split('=')[1].Trim());
}
return pairs;
}
public static IHtmlString EnumToSelectList(this HtmlHelper htmlHelper, T enumSource, string selectedValue) where T : struct
{
var list = new TagBuilder("select");
foreach (T item in Enum.GetValues(typeof(T)).Cast())
{
var option = new TagBuilder("option");
//option.MergeAttribute("value",(int)item);
option.SetInnerText(item.ToString());
list.InnerHtml += option.ToString();
}
return new HtmlString(list.ToString());
}
}