Showing posts with label MVC. Show all posts
Showing posts with label MVC. Show all posts

Sunday, February 2, 2020

Forms Authentication in MVC

index.cshtml

@using (Html.BeginForm("index","home",FormMethod.Post))
{
    @Html.AntiForgeryToken()

    <span>Enter Name</span>
    <input type="text" name="name"  required />

    <input type="submit"  value="Submit" />

}

HomeController.cs
        

        using System.Web.Security;

 [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Index(FormCollection formCollection)
        {

            if (ModelState.IsValid)
            {
                  var authTicket = new FormsAuthenticationTicket(
                    1,// version
                    formCollection["name"].ToString(), // user name
                    DateTime.Now, // created
                    DateTime.Now.AddMinutes(20), // expires
                    false// persistent?
                    "User"  // can be used to store roles
                    );

                string encryptedTicket = FormsAuthentication.Encrypt(authTicket);

                var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);

                System.Web.HttpContext.Current.Response.Cookies.Add(authCookie);         

                return RedirectToAction("about");

            }
            else
            {
                return View();
            }
        }

      
 [Authorize(Roles ="User")]
        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

       
[Authorize]
        public ActionResult logout()
        {

            FormsAuthentication.SignOut();
            return RedirectToAction("index");      
       
        }


Inside the Global.asax.cs


using System.Security.Principal;
using System.Web.Security;

        protected void Application_AuthenticateRequest(Object sender, EventArgs e)
        {
            HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];

            if (authCookie == null || authCookie.Value == "")
                return;

            FormsAuthenticationTicket authTicket;

            try
            {
                authTicket = FormsAuthentication.Decrypt(authCookie.Value);
            }
            catch
            {
                return;
            }

            // retrieve roles from UserData
            string[] roles = authTicket.UserData.Split(';');

            if (Context.User != null)
                Context.User = new GenericPrincipal(Context.User.Identity, roles);

        }




Inside the web.config


  <authentication mode="Forms" >
    <forms defaultUrl="home/index" loginUrl="home/index"  protection="All"></forms>
  </authentication>

  <authorization>
    <allow users="*"/>
    <deny users="?"/>
  </authorization>

Saturday, January 26, 2019

Paging, search & sorting using the datatable.js library


For implementing paging,search & sorting using the datatable.js library.

<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.css">

<table id="table_id" class="display">
    <thead>
        <tr>
            <th>Name</th>
            <th>DOB</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Amar</td>
            <td>10-10-2010</td>
        </tr>
        <tr>
            <td>Akbar</td>
            <td>20-11-2010</td>
        </tr>
    </tbody>
</table>

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.js"></script>

<script>
    $(document).ready(function () {
        $('#table_id').DataTable();
    });
</script>

Jquery UI Multiple Search MVC



For creating autocomplete multiple select using the jquery UI plugin.

<link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

<label>Search fruits:</label>
<input type="text" id="txtFruits" name="txtFruits" />

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<script type="text/javascript">
    $(function () {

        function split(val) {
            return val.split(/,\s*/);
        }
        function extractLast(term) {
            return split(term).pop();
        }

        $("#txtFruits")
      .on("keydown", function (event) {
          if (event.keyCode === $.ui.keyCode.TAB &&
              $(this).autocomplete("instance").menu.active) {
              event.preventDefault();
          }
      })
        .autocomplete({
            source: function (request, response) {
                $.getJSON('@Url.Action("data")', {
                    term: extractLast(request.term)
                }, response);
            },
            focus: function () {
                // prevent value inserted on focus
                return false;
            },
            select: function (event, ui) {
                var terms = split(this.value);
                // remove the current input
                terms.pop();
                // add the selected item
                terms.push(ui.item.value);
                // add placeholder to get the comma-and-space at the end
                terms.push("");
                this.value = terms.join(", ");
                return false;
            }
        });
    })
</script>


        /// <summary>
        /// Inside the controller
        /// Don't change the parameter name (term) it's default by jquery ui
        /// </summary>


public ActionResult data(string term)
        {
            var items = new[] { "Apple", "Pear", "Banana", "Pineapple", "Peach" };

            var filteredItems = items.Where(item => item.IndexOf(term, StringComparison.InvariantCultureIgnoreCase) >= 0 );

            return Json(filteredItems, JsonRequestBehavior.AllowGet);
        }

Git Commands

Git Version   To check the git version Git -v       Git Clone To clone the repository, use the following command: Git clone [u...