Monday, October 26, 2015

MVC Ajax WebGrid with Administrator Buttons

This article is about an MVC Ajax WebGrid with Administrator Buttons and Sorting and Paging . 
  Here we see how to build an Ajax enabled WebGrid , which in case of an User Administrator will display management buttons (Edit - Delete) , and otherwise will not.

In case of an Administrator, the WebGrid will be displayed like this:

MVC Ajax WebGrid with Administrator Buttons





In case of a common User, the WebGrid will be displayed this way:
MVC Ajax WebGrid with Administrator Buttons



All the code in this tutorial , can be downloaded from the following GitHub repository:
https://github.com/CarmelSoftware/MVC_WebGrid_Admin

This is how this Administrator's Ajax WebGrid is shown in a Mobile Emulator :

MVC Ajax WebGrid with Administrator Buttons

In the case of a common User:

MVC Ajax WebGrid with Administrator Buttons



MVC Ajax WebGrid with Administrator Buttons


The whole code for creating this Ajax WebGrid with Management functionality , can be obtained from the following GitHub rep:
https://github.com/CarmelSoftware/MVC_WebGrid_Admin


Add the following markup  to the "Index" view:

@model IEnumerable<MyGrid_BL.Blog>

@{
    ViewBag.Title =  "Ajax WebGrid with Administrator Role Check";
    WebGrid grid = new WebGrid(Model, new[] { "Title", "Text", "DatePosted", "MainPicture", "Blogger" },
        rowsPerPage:2,ajaxUpdateContainerId:"GridDiv");

    IEnumerable<WebGridColumn> oColumns = new[] {

        grid.Column("ID",format:(item) =>  item.GetSelectLink(item.BlogID.ToString()) ) ,
        grid.Column("Title",format:@<a href='/Blog/Details/@item.BlogID'><b>@item.Title</b></a>),
        grid.Column("DatePosted","DatePosted", (item) => String.Format("{0:dd/MM/yyyy}", item.DatePosted != null ? item.DatePosted : DateTime.Now )),
        grid.Column("Picture",format:(item) =>
        { return new MvcHtmlString("<a href='/Blog/Details/" + item.BlogID +
            "'><img src='/Images/"+item.MainPicture+"' style='width:100px;height:100px;'></img></a>");
        })
    };

    if (User.IsInRole("Admin"))
    {
        oColumns = oColumns.Concat(new[] {grid.Column(
            format:@<div class="ActionsTH">
            @Html.ActionLink("Edit", "Edit", new { id=item.BlogID })<br />
            @Html.ActionLink("Details", "Details", new { id=item.BlogID })<br />
            @Html.ActionLink("Delete", "Delete", new { id=item.BlogID })
        </div>) });
    }
    
}

<h2>@ViewData["Title"]</h2>

<div id="GridDiv">
    @grid.GetHtml(tableStyle:"webgrid-tableStyle",headerStyle:"webgrid-headerStyle",footerStyle:"webgrid-footerStyle",alternatingRowStyle:"webgrid-alternatingRowStyle",columns: oColumns) </div>
<p style="text-align:center;">
     
    <input type="button"   value="Create New" onclick="javascript:location='/Blog/Create'" class="btn btn-default"/>
</p>



This code enable the Management Buttons on the Grid, only in case of a Power User such as an Administrator.

The code to set some User to the "Admin" Role, must be added to the "Acount" Controller, at the Register Action, and is as follows:

[HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                try
                {
                    if (!Roles.RoleExists("Admin"))
                    {
                        Roles.CreateRole("Admin");
                    }
                    WebSecurity.CreateUserAndAccount(model.UserName, model.Password);

                    string sAdmins = ConfigurationManager.AppSettings["Admins"];
                    string[] oAdmins = sAdmins.Split(';');

                    WebSecurity.Login(model.UserName, model.Password);

                    foreach (string sAdmin in oAdmins)
                    {
                        if (string.Compare(model.UserName, sAdmin) == 0
                                                &&
                            !Roles.IsUserInRole("Admin"))
                        {
                            Roles.AddUserToRole(model.UserName, "Admin");
                        }
                    }



                    return RedirectToAction("Index", "Home");
                }
                catch (MembershipCreateUserException e)
                {
                    ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

And these are the AppSettings to the Web.config file:


<appSettings>
    <add key="Admins" value="sa;sa1;sa2;sa3"/>
  </appSettings>

As you can see, we also reference a "~/Content/WebGrid.css" file:


body {
    background: #f7f3de url("images/ui-bg_fine-grain_15_f7f3de_60x60.png") 50% 50% repeat;
}

.webgrid-tableStyle {
    font: italic 11px Verdana;
    width: 100%;
    display: grid;
    border-collapse: separate;
    border: solid 1px #98BF21;
    background: #f8f7f6 url("images/ui-bg_fine-grain_10_f8f7f6_60x60.png") 50% 50% repeat;
    padding: 5px 5px 5px 5px;
    text-align: center;
    border-radius:10px;
}

.webgrid-headerStyle th {
    width: 250px;    
    background: #c67f1c url("images/ui-bg_fine-grain_10_eceadf_60x60.png") 50% 50% repeat;
    color: #FFFFFF !important;
    font: 900 14px Verdana !important;
    padding: 5px 5px 5px 5px;
    text-align: center;
    height:50px;
}

.ActionsTH {    
    background: #eceadf url("images/ui-bg_fine-grain_10_eceadf_60x60.png") 50% 50% repeat;
    color: #FFFFFF !important;
    font: 900 14px Verdana !important;
    padding: 5px 5px 5px 5px;
    text-align: center;
    width: 180px;
}

.webgrid-footerStyle, .webgrid-footerStyle a {
    background:#c67f1c url("images/ui-bg_fine-grain_10_eceadf_60x60.png") 50% 50% repeat;
    color: #FFF;
    font: 900 14px Verdana;
    padding: 3px 3px 3px 3px;
    height:50px;
}

.webgrid-alternatingRowStyle {
    background: #f8f7f6 url("images/ui-bg_fine-grain_10_f8f7f6_60x60.png") 50% 50% repeat;
    padding: 5px 5px 5px 5px;
}

.title-column {
    font: 900 13px Verdana;
    text-align: center;
}

.webgrid-img {
    width: 150px;
    height: 150px;
}

.webgrid-tableStyle a {
    text-decoration: none;
    color: #808080;
}
select {
      width: 200px;
    }


Important:
If you do not see the Ajax working  , it can be because some jQuery scripts are missing.
Just cut the jQuery.js file from the _Layout file to the <head> tag :
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/jqueryui")
</head>



To install a Mobile Emulator, take a look at this tutorial on installing the FREE Ripple Emulator.


That's all. Our Administrator WebGrid will be displayed this way:

MVC Ajax WebGrid with Administrator Buttons

MVC Ajax WebGrid with Administrator Buttons






      by Carmel Schvartzman


כתב: כרמל שוורצמן