Sunday, July 27, 2014

Master Page & ViewStart in ASP.Net MVC 4

Master Page & ViewStart in ASP.Net MVC 4

In this blog, I am going to tell you how to create a master page or layout page and how to use the master page in other views as well as view start in asp.net mvc 4

Step 1

First create an empty asp.net mvc 4 application and add a folder named “Shared” in the View folder and add a view named “_LayoutView” in the Shared folder and write the following code in it.
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Layout View</title>
</head>
<body>
    <div>
        <div id="HeaderContainer" style="width:100%;font-size:25px;padding:10px;">
            <div style="width:25%;display:inline;">
                @Html.ActionLink("Home", "Index","Home")
            </div>
            <div style="width:25%;display:inline">
                @Html.ActionLink("Services", "Services", "Home")
            </div>
            <div style="width:25%;display:inline">
                @Html.ActionLink("About Us", "AboutUs","Home")
            </div>
            <div style="width:25%;display:inline">
                @Html.ActionLink("Contact Us", "ContactUs","Home")
            </div>
        </div>
        <div id="BodyContainer" style="width:100%;height:300px;">
            @RenderBody()
        </div>
        <div id="FootContainer" style="width:100%;height:100px;">
            <p>Copyright : SUMITKESARWANI.BLOGSPOT.IN</p>
        </div>
    </div>
</body>
</html>

This view will behave as master page or layout page for this project.

Step 2


Now add a controller named “HomeController” and write the below code in it:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MasterPageMvcApp.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Services()
        {
            return View();
        }

        public ActionResult AboutUs()
        {
            return View();
        }

        public ActionResult ContactUs()
        {
            return View();
        }
    }
}

Step 3

Now add a view named “Index” like this:





Select checkbox of master page and click on browse:





Select the _LayoutView and click on ok.

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_LayoutView.cshtml";
}

<h2>Home</h2>

Now add the view for Services, About Us and Contact Us like above.

Step 4


Now run the application




Click on Services:







To add the master page in each view, we have added the Layout Property on the top of the view and set the path of the master page.

@{
    Layout = "~/Views/Shared/_LayoutView.cshtml";
}

Now suppose we have 50 views in a project then we have to set the layout property in each view.

In future, if you change the master page name or location then you has to make the changes in each view in the project, this will be very tidy and time taken process.

To avoid this tidy process, you can use the ViewStart view.


ViewStart

ViewStart is the view which is applied to all other views automatically. We set the layout property in the ViewStart view and the layout property will be added to all other views automatically.

ViewStart view will rendered first from all the other views.

If you want to update the master page name or location, then you can simply change it in the ViewStart view and it will update it in all the other views.

Now in the above project, delete the layout property from all the views:

Layout = "~/Views/Shared/_LayoutView.cshtml"; // delete it from all the views

And add a view named “_ViewStart” in the view folder and add the layout property like this:

@{
   
    Layout = "~/Views/Shared/_LayoutView.cshtml";
}

Your Solution Explorer will look like this:




Now run the application:





You can see that the master page is rendered from the ViewStart view.



Thank you for reading this article, please put your valuable comment or any suggestion/question in the comment box. 








Friday, July 25, 2014

FormsAuthentication in ASP.Net MVC 4

FormsAuthentication in ASP.Net MVC 4

In this blog, I am going to explain the forms authentication in asp.net mvc 4 and how to implement it in our project.

In the following example I’m going to use the Entity Framework, so if you want to learn the Entity Framework first then you can read my blog on Entity Framework here:



Step 1

First create two tables in the database named “Login” and “StudentInformation” like this:





And have some dummy data in both the tables:


Step 2

Now create an empty asp.net mvc 4 web application with razor engine and add a model class to the project named “LoginInformation” like this:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace FormAuthenticationMvcApp.Models
{
    [Table("Login")]
    public class LoginInformation
    {
        [Key]
        [Display(Name="Username")]
        [Required(ErrorMessage="Username is mandatory")]
        public string username { get; set; }

        [Display(Name="Password")]
        [Required(ErrorMessage="Password is mandatory")]
        public string password { get; set; }
    }
}


Now create another model class named “StudentInformation” like this:


using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace FormAuthenticationMvcApp.Models
{
    [Table("StudentInformation")]
    public class StudentInformation
    {
        [Key] //Primary Key
        public int StudentId { get; set; }

        [Display(Name = "NAME")]
        public string Name { get; set; }

        [Display(Name = "AGE")]
        public string Age { get; set; }

        [Display(Name = "ADDRESS")]
        public string Address { get; set; }

        [Display(Name = "COURSE")]
        public string Course { get; set; }
    }
}

Step 3

Now create a DbContext class named “StudentDbContext” like this:

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace FormAuthenticationMvcApp.Models
{
    public class StudentDbContext : DbContext
    {
        public DbSet<StudentInformation> Student { get; set; }
        public DbSet<LoginInformation> Login { get; set; }
    }
}

Step 4

Create a connection string in the web.config like this:

<connectionStrings>
    <add name="StudentDbContext" connectionString="Data Source=DELL-PC; Initial Catalog=StudentDB; Integrated Security = true;"providerName="System.Data.SqlClient"/>
  </connectionStrings>

The important thing to notice here is that the name of the connectionString is same as the DbContext class that we have created. If we keep the name of the connectionString same as the DbContext class the corresponding DbContext class will use the connectionString to persist the data, but this is also flexible so that we have the possiblity of giving custom names to the connectionStrings.


Now add the authentication tag under the system.web tag in the web.config file like this:

<authentication mode="Forms">
    <forms loginUrl="~/Home/UserLogin" timeout="2880"></forms>
</authentication>


Step 5

Now add a controller to the project named “HomeController” and write the below in it:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using FormAuthenticationMvcApp.Models;

namespace FormAuthenticationMvcApp.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        StudentDbContext context = new StudentDbContext();
       
        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]
        public ActionResult UserLogin()
        {
            return View();
        }

        [HttpPost]
        public ActionResult UserLogin(LoginInformation login)
        {
            if (ModelState.IsValid)
            {
                int count = context.Login.Where(m => m.username == login.username && m.password == login.password).Count();
                if (count > 0)
                {
                    FormsAuthentication.SetAuthCookie(login.username, false);
                    return RedirectToAction("Student");
                }
            }

            return View();
        }

        [Authorize]
        public ActionResult Student()
        {
            IEnumerable<StudentInformation> student = context.Student.ToList();
            return View(student);
        }

        public ActionResult UserLogout()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Index");
        }

    }
}

Step 6

Now add views to the project:


Index View

@{
    ViewBag.Title = "Index";
}


<div>
    <h2>Welcome</h2>
    <br />
    @Html.ActionLink("Login","UserLogin")
</div>

UserLogin View

@model FormAuthenticationMvcApp.Models.LoginInformation

@{
    ViewBag.Title = "UserLogin";
}

<h2>Login</h2>
<br />
<div >
    @using (Html.BeginForm("UserLogin","Home", FormMethod.Post))
    {
        <fieldset>
            <legend>Login</legend>
            <div>
                @Html.LabelFor(m=>m.username)
                @Html.TextBoxFor(m=>m.username)
                @Html.ValidationMessageFor(m=>m.username)
            </div>
            <div>
                @Html.LabelFor(m=>m.password)
                @Html.PasswordFor(m=>m.password)
                @Html.ValidationMessageFor(m=>m.password)
            </div>
            <div>
                <input type="submit" value="Submit"/>
            </div>
        </fieldset>
       
    }
</div>

Student View

@model IEnumerable<FormAuthenticationMvcApp.Models.StudentInformation>

@{
    ViewBag.Title = "Student";
}

<h2>Student</h2>

<p>
    @Html.ActionLink("Logout", "UserLogout")
</p>
<table>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Age)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Address)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Course)
        </th>
        <th></th>
    </tr>

    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Name)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Age)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Address)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Course)
            </td>
        </tr>
    }

</table>

After doing all the above stuff, your solution explorer will look like this:


Output

Now run the application:



Click on Login:



Fill up the form and click on submit:





Now click on logout - it will redirect you to the index view:




Thank you for reading this article, please put your valuable comment or any suggestion/question in the comment box.