European ASP.NET MVC 4 and MVC 5 Hosting

BLOG about ASP.NET MVC 3, ASP.NET MVC 4, and ASP.NET MVC 5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

ASP.NET MVC Hosting - HostForLIFE.eu :: Building an ASP.NET MVC 5 Website with Custom Bootstrap Templates

clock November 3, 2026 12:09 by author Peter

Recently, I have struggled with a problem of how I would use custom free templates in my ASP.NET MVC project rather than using default ones. Here are the steps in making a beautiful bootstrap site using ASP.NET MVC 5.

Download a free template or you can buy a premium template if you want. For our example, we will be using the free Freelancer template. After downloading, you should get the following files.

Open Visual Studio and create an ASP.NET Web Application.

In configuring, the application must be MVC.
I included Web API because I used them a lot in my application.
The last part is very important, because it’s very hard to add an authentication module once the project has been created, trust me, based on experience.

Once the project has been created, the next thing that we should do is copy the files from our downloaded template to our project. Make sure to overwrite any directories of the same name.

Open the BundleConfig.cs file in the App_Start directory and comment all contents in theRegisterBundles method as shown in the image below:

Now we will modify the Views. In modifying the Views, all you need to do is open the Index.html file included in the template and copy it to the corresponding Views.
The first View that will be modified is the _Layout. cshtml, which is located in the Views\Shared folder. Delete all the content and replace it with the code below.
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <!-- Bootstrap Core CSS -->
    <link href="/css/bootstrap.min.css" rel="stylesheet">
    <!-- Custom CSS -->
    <link href="~/css/freelancer.css" rel="stylesheet">
    <!-- Custom Fonts -->
    <link href="/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">

    <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
    <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <!--[endif]-->
</head>

<body id="page-top" data-spy="scroll" data-target=".navbar-fixed-top">
@RenderBody()
</body>
</html>


Next, is to modify the Index. cshtml, which is located in Views\Home. Delete all the content and replace it with the code below.
<!DOCTYPE  html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <meta name="description" content="" />
        <meta name="author" content="" />

        <title>Freelancer - Start Bootstrap Theme</title>

        <!-- Bootstrap Core CSS - Uses Bootswatch Flatly Theme: http://bootswatch.com/flatly/ -->
        <link href="css/bootstrap.min.css" rel="stylesheet" />

        <!-- Custom CSS -->
        <link href="css/freelancer.css" rel="stylesheet" />

        <!-- Custom Fonts -->
        <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css" />
        <link href="http://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css" />
        <link href="http://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet" type="text/css" />

        <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
        <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
        <!--[if  lt IE 9]>
            <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
            <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
        <![endif]-->
    </head>

    <body id="page-top" class="index">
        <!-- Navigation -->
        <nav class="navbar navbar-default navbar-fixed-top">
            <div class="container">
                <!-- Brand and toggle get grouped for better mobile display -->
                <div class="navbar-header page-scroll">
                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                        <span class="sr-only">Toggle navigation</span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
                    <a class="navbar-brand" href="#page-top">Start Bootstrap</a>
                </div>

                <!-- Collect the nav links, forms, and other content for toggling -->
                <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                    <ul class="nav navbar-nav navbar-right">
                        <li class="hidden">
                            <a href="#page-top"></a>
                        </li>
                        <li class="page-scroll">
                            <a href="#portfolio">Portfolio</a>
                        </li>
                        <li class="page-scroll">
                            <a href="#about">About</a>
                        </li>
                        <li class="page-scroll">
                            <a href="#contact">Contact</a>
                        </li>
                    </ul>
                </div>
                <!-- /.navbar-collapse -->
            </div>
            <!-- /.container-fluid -->
        </nav>

        <!-- Header -->
        <header>
            <div class="container">
                <div class="row">
                    <div class="col-lg-12">
                        <img class="img-responsive" src="img/profile.png" alt="" />
                        <div class="intro-text">
                            <span class="name">Start Bootstrap</span>
                            <hr class="star-light" />
                            <span class="skills">Web Developer - Graphic Artist - User Experience Designer</span>
                        </div>
                    </div>
                </div>
            </div>
        </header>

        <!-- Portfolio Grid Section -->
        <section id="portfolio">
            <div class="container">
                <div class="row">
                    <div class="col-lg-12 text-center">
                        <h2>Portfolio</h2>
                        <hr class="star-primary" />
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-4 portfolio-item">
                        <a href="#portfolioModal1" class="portfolio-link" data-toggle="modal">
                            <div class="caption">
                                <div class="caption-content">
                                    <i class="fa fa-search-plus fa-3x"></i>
                                </div>
                            </div>
                            <img src="img/portfolio/cabin.png" class="img-responsive" alt="" />
                        </a>
                    </div>
                    <div class="col-sm-4 portfolio-item">
                        <a href="#portfolioModal2" class="portfolio-link" data-toggle="modal">
                            <div class="caption">
                                <div class="caption-content">
                                    <i class="fa fa-search-plus fa-3x"></i>
                                </div>
                            </div>
                            <img src="img/portfolio/cake.png" class="img-responsive" alt="" />
                        </a>
                    </div>
                    <div class="col-sm-4 portfolio-item">
                        <a href="#portfolioModal3" class="portfolio-link" data-toggle="modal">
                            <div class="caption">
                                <div class="caption-content">
                                    <i class="fa fa-search-plus fa-3x"></i>
                                </div>
                            </div>
                            <img src="img/portfolio/circus.png" class="img-responsive" alt="" />
                        </a>
                    </div>
                    <div class="col-sm-4 portfolio-item">
                        <a href="#portfolioModal4" class="portfolio-link" data-toggle="modal">
                            <div class="caption">
                                <div class="caption-content">
                                    <i class="fa fa-search-plus fa-3x"></i>
                                </div>
                            </div>
                            <img src="img/portfolio/game.png" class="img-responsive" alt="" />
                        </a>
                    </div>
                    <div class="col-sm-4 portfolio-item">
                        <a href="#portfolioModal5" class="portfolio-link" data-toggle="modal">
                            <div class="caption">
                                <div class="caption-content">
                                    <i class="fa fa-search-plus fa-3x"></i>
                                </div>
                            </div>
                            <img src="img/portfolio/safe.png" class="img-responsive" alt="" />
                        </a>
                    </div>
                    <div class="col-sm-4 portfolio-item">
                        <a href="#portfolioModal6" class="portfolio-link" data-toggle="modal">
                            <div class="caption">
                                <div class="caption-content">
                                    <i class="fa fa-search-plus fa-3x"></i>
                                </div>
                            </div>
                            <img src="img/portfolio/submarine.png" class="img-responsive" alt="" />
                        </a>
                    </div>
                </div>
            </div>
        </section>

        <!-- About Section -->
        <section class="success" id="about">
            <div class="container">
                <div class="row">
                    <div class="col-lg-12 text-center">
                        <h2>About</h2>
                        <hr class="star-light" />
                    </div>
                </div>
                <div class="row">
                    <div class="col-lg-4 col-lg-offset-2">
                        <p>Freelancer is a free bootstrap theme created by Start Bootstrap. The download includes the complete source files including HTML, CSS, and JavaScript as well as optional LESS stylesheets for easy customization.</p>
                    </div>
                    <div class="col-lg-4">
                        <p>Whether you're a student looking to showcase your work, a professional looking to attract clients, or a graphic artist looking to share your projects, this template is the perfect starting point!</p>
                    </div>
                    <div class="col-lg-8 col-lg-offset-2 text-center">
                        <a href="#" class="btn btn-lg btn-outline"> <i class="fa fa-download"></i> Download Theme </a>
                    </div>
                </div>
            </div>
        </section>

        <!-- Contact Section -->
        <section id="contact">
            <div class="container">
                <div class="row">
                    <div class="col-lg-12 text-center">
                        <h2>Contact Me</h2>
                        <hr class="star-primary" />
                    </div>
                </div>
                <div class="row">
                    <div class="col-lg-8 col-lg-offset-2">
                        <!-- To configure the contact form email address, go to mail/contact_me.php and update the email address in the PHP file on line 19. -->
                        <!-- The form should work on most web servers, but if the form is not working you may need to configure your web server differently. -->
                        <form name="sentMessage" id="contactForm" novalidate>
                            <div class="row control-group">
                                <div class="form-group col-xs-12 floating-label-form-group controls">
                                    <label>Name</label>
                                    <input type="text" class="form-control" placeholder="Name" id="name" required data-validation-required-message="Please enter your name." />
                                    <p class="help-block text-danger"></p>
                                </div>
                            </div>
                            <div class="row control-group">
                                <div class="form-group col-xs-12 floating-label-form-group controls">
                                    <label>Email Address</label>
                                    <input type="email" class="form-control" placeholder="Email Address" id="email" required data-validation-required-message="Please enter your email address." />
                                    <p class="help-block text-danger"></p>
                                </div>
                            </div>
                            <div class="row control-group">
                                <div class="form-group col-xs-12 floating-label-form-group controls">
                                    <label>Phone Number</label>
                                    <input type="tel" class="form-control" placeholder="Phone Number" id="phone" required data-validation-required-message="Please enter your phone number." />
                                    <p class="help-block text-danger"></p>
                                </div>
                            </div>
                            <div class="row control-group">
                                <div class="form-group col-xs-12 floating-label-form-group controls">
                                    <label>Message</label>
                                    <textarea rows="5" class="form-control" placeholder="Message" id="message" required data-validation-required-message="Please enter a message."></textarea>
                                    <p class="help-block text-danger"></p>
                                </div>
                            </div>
                            <br />
                            <div id="success"></div>
                            <div class="row">
                                <div class="form-group col-xs-12">
                                    <button type="submit" class="btn btn-success btn-lg">Send</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </section>

        <!-- Footer -->
        <footer class="text-center">
            <div class="footer-above">
                <div class="container">
                    <div class="row">
                        <div class="footer-col col-md-4">
                            <h3>Location</h3>
                            <p>
                                3481 Melrose Place<br />
                                Beverly Hills, CA 90210
                            </p>
                        </div>
                        <div class="footer-col col-md-4">
                            <h3>Around the Web</h3>
                            <ul class="list-inline">
                                <li>
                                    <a href="#" class="btn-social btn-outline"><i class="fa fa-fw fa-facebook"></i></a>
                                </li>
                                <li>
                                    <a href="#" class="btn-social btn-outline"><i class="fa fa-fw fa-google-plus"></i></a>
                                </li>
                                <li>
                                    <a href="#" class="btn-social btn-outline"><i class="fa fa-fw fa-twitter"></i></a>
                                </li>
                                <li>
                                    <a href="#" class="btn-social btn-outline"><i class="fa fa-fw fa-linkedin"></i></a>
                                </li>
                                <li>
                                    <a href="#" class="btn-social btn-outline"><i class="fa fa-fw fa-dribbble"></i></a>
                                </li>
                            </ul>
                        </div>
                        <div class="footer-col col-md-4">
                            <h3>About Freelancer</h3>
                            <p>Freelance is a free to use, open source Bootstrap theme created by <a href="http://startbootstrap.com">Start Bootstrap</a>.</p>
                        </div>
                    </div>
                </div>
            </div>
            <div class="footer-below">
                <div class="container">
                    <div class="row">
                        <div class="col-lg-12">
                            Copyright © Your Website 2026
                        </div>
                    </div>
                </div>
            </div>
        </footer>

        <!-- Scroll to Top Button (Only visible on small and extra-small screen sizes) -->
        <div class="scroll-top page-scroll visible-xs visible-sm">
            <a class="btn btn-primary" href="#page-top">
                <i class="fa fa-chevron-up"></i>
            </a>
        </div>

        <!-- Portfolio Modals -->
        <div class="portfolio-modal modal fade" id="portfolioModal1" tabindex="-1" role="dialog" aria-hidden="true">
            <div class="modal-content">
                <div class="close-modal" data-dismiss="modal">
                    <div class="lr">
                        <div class="rl"></div>
                    </div>
                </div>
                <div class="container">
                    <div class="row">
                        <div class="col-lg-8 col-lg-offset-2">
                            <div class="modal-body">
                                <h2>Project Title</h2>
                                <hr class="star-primary" />
                                <img src="img/portfolio/cabin.png" class="img-responsive img-centered" alt="" />
                                <p>
                                    Use this area of the page to describe your project. The icon above is part of a free icon set by
                                    <a href="https://sellfy.com/p/8Q9P/jV3VZ/">Flat Icons</a>. On their website, you can download their free set with 16 icons, or you can purchase the entire set with 146 icons for only $12!
                                </p>
                                <ul class="list-inline item-details">
                                    <li>
                                        Client:
                                        <strong>
                                            <a href="http://startbootstrap.com">Start Bootstrap</a>
                                        </strong>
                                    </li>
                                    <li>
                                        Date:
                                        <strong>
                                            <a href="http://startbootstrap.com">April 2026</a>
                                        </strong>
                                    </li>
                                    <li>
                                        Service:
                                        <strong>
                                            <a href="http://startbootstrap.com">Web Development</a>
                                        </strong>
                                    </li>
                                </ul>
                                <button type="button" class="btn btn-default" data-dismiss="modal"><i class="fa fa-times"></i> Close</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="portfolio-modal modal fade" id="portfolioModal2" tabindex="-1" role="dialog" aria-hidden="true">
            <div class="modal-content">
                <div class="close-modal" data-dismiss="modal">
                    <div class="lr">
                        <div class="rl"></div>
                    </div>
                </div>
                <div class="container">
                    <div class="row">
                        <div class="col-lg-8 col-lg-offset-2">
                            <div class="modal-body">
                                <h2>Project Title</h2>
                                <hr class="star-primary" />
                                <img src="img/portfolio/cake.png" class="img-responsive img-centered" alt="" />
                                <p>
                                    Use this area of the page to describe your project. The icon above is part of a free icon set by
                                    <a href="https://sellfy.com/p/8Q9P/jV3VZ/">Flat Icons</a>. On their website, you can download their free set with 16 icons, or you can purchase the entire set with 146 icons for only $12!
                                </p>
                                <ul class="list-inline item-details">
                                    <li>
                                        Client:
                                        <strong>
                                            <a href="http://startbootstrap.com">Start Bootstrap</a>
                                        </strong>
                                    </li>
                                    <li>
                                        Date:
                                        <strong>
                                            <a href="http://startbootstrap.com">April 2026</a>
                                        </strong>
                                    </li>
                                    <li>
                                        Service:
                                        <strong>
                                            <a href="http://startbootstrap.com">Web Development</a>
                                        </strong>
                                    </li>
                                </ul>
                                <button type="button" class="btn btn-default" data-dismiss="modal"><i class="fa fa-times"></i> Close</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="portfolio-modal modal fade" id="portfolioModal3" tabindex="-1" role="dialog" aria-hidden="true">
            <div class="modal-content">
                <div class="close-modal" data-dismiss="modal">
                    <div class="lr">
                        <div class="rl"></div>
                    </div>
                </div>
                <div class="container">
                    <div class="row">
                        <div class="col-lg-8 col-lg-offset-2">
                            <div class="modal-body">
                                <h2>Project Title</h2>
                                <hr class="star-primary" />
                                <img src="img/portfolio/circus.png" class="img-responsive img-centered" alt="" />
                                <p>
                                    Use this area of the page to describe your project. The icon above is part of a free icon set by
                                    <a href="https://sellfy.com/p/8Q9P/jV3VZ/">Flat Icons</a>. On their website, you can download their free set with 16 icons, or you can purchase the entire set with 146 icons for only $12!
                                </p>
                                <ul class="list-inline item-details">
                                    <li>
                                        Client:
                                        <strong>
                                            <a href="http://startbootstrap.com">Start Bootstrap</a>
                                        </strong>
                                    </li>
                                    <li>
                                        Date:
                                        <strong>
                                            <a href="http://startbootstrap.com">April 2026</a>
                                        </strong>
                                    </li>
                                    <li>
                                        Service:
                                        <strong>
                                            <a href="http://startbootstrap.com">Web Development</a>
                                        </strong>
                                    </li>
                                </ul>
                                <button type="button" class="btn btn-default" data-dismiss="modal"><i class="fa fa-times"></i> Close</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="portfolio-modal modal fade" id="portfolioModal4" tabindex="-1" role="dialog" aria-hidden="true">
            <div class="modal-content">
                <div class="close-modal" data-dismiss="modal">
                    <div class="lr">
                        <div class="rl"></div>
                    </div>
                </div>
                <div class="container">
                    <div class="row">
                        <div class="col-lg-8 col-lg-offset-2">
                            <div class="modal-body">
                                <h2>Project Title</h2>
                                <hr class="star-primary" />
                                <img src="img/portfolio/game.png" class="img-responsive img-centered" alt="" />
                                <p>
                                    Use this area of the page to describe your project. The icon above is part of a free icon set by
                                    <a href="https://sellfy.com/p/8Q9P/jV3VZ/">Flat Icons</a>. On their website, you can download their free set with 16 icons, or you can purchase the entire set with 146 icons for only $12!
                                </p>
                                <ul class="list-inline item-details">
                                    <li>
                                        Client:
                                        <strong>
                                            <a href="http://startbootstrap.com">Start Bootstrap</a>
                                        </strong>
                                    </li>
                                    <li>
                                        Date:
                                        <strong>
                                            <a href="http://startbootstrap.com">April 2026</a>
                                        </strong>
                                    </li>
                                    <li>
                                        Service:
                                        <strong>
                                            <a href="http://startbootstrap.com">Web Development</a>
                                        </strong>
                                    </li>
                                </ul>
                                <button type="button" class="btn btn-default" data-dismiss="modal"><i class="fa fa-times"></i> Close</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="portfolio-modal modal fade" id="portfolioModal5" tabindex="-1" role="dialog" aria-hidden="true">
            <div class="modal-content">
                <div class="close-modal" data-dismiss="modal">
                    <div class="lr">
                        <div class="rl"></div>
                    </div>
                </div>
                <div class="container">
                    <div class="row">
                        <div class="col-lg-8 col-lg-offset-2">
                            <div class="modal-body">
                                <h2>Project Title</h2>
                                <hr class="star-primary" />
                                <img src="img/portfolio/safe.png" class="img-responsive img-centered" alt="" />
                                <p>
                                    Use this area of the page to describe your project. The icon above is part of a free icon set by
                                    <a href="https://sellfy.com/p/8Q9P/jV3VZ/">Flat Icons</a>. On their website, you can download their free set with 16 icons, or you can purchase the entire set with 146 icons for only $12!
                                </p>
                                <ul class="list-inline item-details">
                                    <li>
                                        Client:
                                        <strong>
                                            <a href="http://startbootstrap.com">Start Bootstrap</a>
                                        </strong>
                                    </li>
                                    <li>
                                        Date:
                                        <strong>
                                            <a href="http://startbootstrap.com">April 2026</a>
                                        </strong>
                                    </li>
                                    <li>
                                        Service:
                                        <strong>
                                            <a href="http://startbootstrap.com">Web Development</a>
                                        </strong>
                                    </li>
                                </ul>
                                <button type="button" class="btn btn-default" data-dismiss="modal"><i class="fa fa-times"></i> Close</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="portfolio-modal modal fade" id="portfolioModal6" tabindex="-1" role="dialog" aria-hidden="true">
            <div class="modal-content">
                <div class="close-modal" data-dismiss="modal">
                    <div class="lr">
                        <div class="rl"></div>
                    </div>
                </div>
                <div class="container">
                    <div class="row">
                        <div class="col-lg-8 col-lg-offset-2">
                            <div class="modal-body">
                                <h2>Project Title</h2>
                                <hr class="star-primary" />
                                <img src="img/portfolio/submarine.png" class="img-responsive img-centered" alt="" />
                                <p>
                                    Use this area of the page to describe your project. The icon above is part of a free icon set by
                                    <a href="https://sellfy.com/p/8Q9P/jV3VZ/">Flat Icons</a>. On their website, you can download their free set with 16 icons, or you can purchase the entire set with 146 icons for only $12!
                                </p>
                                <ul class="list-inline item-details">
                                    <li>
                                        Client:
                                        <strong>
                                            <a href="http://startbootstrap.com">Start Bootstrap</a>
                                        </strong>
                                    </li>
                                    <li>
                                        Date:
                                        <strong>
                                            <a href="http://startbootstrap.com">April 2026</a>
                                        </strong>
                                    </li>
                                    <li>
                                        Service:
                                        <strong>
                                            <a href="http://startbootstrap.com">Web Development</a>
                                        </strong>
                                    </li>
                                </ul>
                                <button type="button" class="btn btn-default" data-dismiss="modal"><i class="fa fa-times"></i> Close</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- jQuery -->
        <script src="js/jquery.js"></script>

        <!-- Bootstrap Core JavaScript -->
        <script src="js/bootstrap.min.js"></script>

        <!-- Plugin JavaScript -->
        <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js"></script>
        <script src="js/classie.js"></script>
        <script src="js/cbpAnimatedHeader.js"></script>

        <!-- Contact Form JavaScript -->
        <script src="js/jqBootstrapValidation.js"></script>
        <script src="js/contact_me.js"></script>

        <!-- Custom Theme JavaScript -->
        <script src="js/freelancer.js"></script>
    </body>
</html>


Now run your project. You should get this beautiful page from your local host.




ASP.NET MVC Hosting - HostForLIFE.eu :: ASP.NET MVC 5 Create Shared Razor Layout And ViewStart

clock October 25, 2019 09:18 by author Peter

In article, I have shared a way to create a Layout Razor and ViewStart in ASP.NET MVC 5.
 
Views/Shared
You need to create a shared folder, "Shared" in the Views directory.
 
Go Views/Shared directory and create new _LayoutPage1.cshtml file and write the following below code.
    <!DOCTYPE html> 
     
    <html> 
    <head> 
        <meta name="viewport" content="width=device-width" /> 
        <title>@ViewBag.Title</title> 
    </head> 
    <body> 
        <div> 
            @RenderBody() 
        </div> 
    </body> 
    </html> 


The @RenderBody()
Use display content in multiple controllers to View.

Example you can have a fixed header and footer in the page. Only change will be the content of the RenderBody() called in the code.
    <html> 
    <head> 
        <meta name="viewport" content="width=device-width" /> 
        <title>@ViewBag.Title</title> 
    </head> 
    <body> 
        <div class="header"> 
            <!--code header fixed--> 
        </div> 
        <div> 
            @RenderBody() 
        </div> 
        <div class="footer"> 
            <!--code footer fixed--> 
        </div> 
    </body> 
    </html> 


So you have fixed the (header/footer) for the website.
 
Okay, you need using _LayoutPage1.cshtml, so you to Views/Home/index.cshtml. Open it, pass the following below code.
    @{ 
        ViewBag.Title = "Index"; 
        Layout = "~/Views/Shared/_LayoutPage1.cshtml"; 
    } 


_ViewStart.cshtml used to define the layout for the website. You can set the layout settings as well, if HomeController is using Layout.
 
_LayoutHome.cshtml or AdminController is _LayoutAdmin.cshtml
    //Views/ViewStart.cshtml 
    @{ 
        Layout = "~/Views/Shared/_LayoutPage1.cshtml"; 
    } 


You can configuration _ViewStart.cshtml the following below code.
    @{ 
     
        string CurrentName = Convert.ToString(HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"]); 
        string clayout = ""; 
        switch (CurrentName) 
        { 
            case "Home": 
                clayout = "~/Views/Shared/_LayoutHome.cshtml"; 
                break; 
            default: 
                //Admin layout   
                clayout = "~/Views/Shared/_LayoutAdmin.cshtml"; 
                break; 
        } 
        Layout = clayout; 
     
    } 

This gives you an idea, how to use a Razor layout in various pages.

 



ASP.NET MVC Hosting - HostForLIFE.eu :: Preventing Cross Site Request Forgery In MVC

clock September 26, 2019 11:14 by author Peter

What is Cross-Site Request Forgery
Cross-Site Request Forgery (CSRF) is a process in which a user first signs on to a genuine website (e.g. facebook.com) and after successful login, the user opens another website (malicious website) in the same browser.
 
Both websites are opened in the same browser. Malicious website will display some links to the user and asks the user to click on those links. User clicks on the links displayed on a malicious website, the malicious website sends a request using the existing session of genuine website. Web server of genuine website treats this request as a valid request and assumes that it is coming from a valid user so it executes the request and provides a proper response. A malicious website can perform harmful operations on genuine website.
 
In order to solve this problem, we expect the Action Method of genuine website to recognize the source of the request, whether the request is coming from genuine website or from a malicious website. This can be achieved by using the [ValidateAntiForgeryToken] attribute in ASP.Net MVC.
 
How to Implement CSRF Security in MVC
In order to implement CSRF security in MVC, first, we need to use HTML helper @Html.AntiForgeryToken() in view. It should be placed inside the BeginForm() method in view.
 
Next, we need to add [ValidateAntiForgeryToken] attribute on the action method which will accept HTTP post request. We need to do only these 2 changes and now MVC will prevent CSRF attacks.
 
How ValidateAntiForgeryToken works
How ValidateAntiForgeryToken prevents CSRF attacks?


First, the user will open genuine website in the browser. User login to genuine website. After login, genuine website sends Authentication cookie and Verification token. Verification token has randomly generated alphanumeric values. The verification token is stored in the cookie as well as in hidden field on client-side. When HTML form is submitted to the server, the verification token is submitted as a cookie as well as a hidden field. On the server-side, both are checked if they are same or not? If both are same then request is valid. If they are different or one of them is missing then request is treated as invalid request and will be rejected automatically by MVC.
 
When a user opens a malicious website in a new tab of the same browser, the malicious website will display some links and ask the user to click on those links. This website already has a script to send the request to genuine website. When the user clicks on links, the malicious website sends a request to genuine website. Since request is being sent to genuine website, the browser automatically submits Authentication cookie to Action method of genuine website but here, the hidden field is missing. The Action method has [ValidateAntiForgeryToken] attribute so it checks whether Authentication cookie and hidden field has same value but here, the hidden field is missing so the request is treated as invalid and it is rejected by MVC.
 
Practical Implementation
Wherever you have a Form, use @Html.AntiForgeryToken() inside the form and action method for accepting the HTTP Post should have ValidateAntiForgeryToken attribute. These are the only change, the rest of the process will be taken care of by ASP.Net MVC.
 
Please see the below HTML view where I have [email protected]()
    @using (Html.BeginForm("Create", "Products", FormMethod.Post, new { enctype = "multipart/form-data" })) 
    { 
       @Html.AntiForgeryToken() 
       <div class="form-row"> 
       <div class="form-group col-md-6"> 
          @Html.LabelFor(temp => temp.ProductName) 
          @Html.TextBoxFor(temp => temp.ProductName, new { placeholder = "Product Name", @class = "form-control" }) 
          @Html.ValidationMessageFor(temp => temp.ProductName) 
       </div> 
    <div class="form-group col-md-6"> 
       @Html.LabelFor(temp=>temp.Price) 
       @Html.TextBoxFor(temp=>temp.Price,new { @class="form-control",placeholder="Price"}) 
    </div> 
    </div> 
    @Html.ValidationSummary() 
       <button type="submit" class="btn btn-success">Create</button> 
       <a class="btn btn-danger" href="/products/index">Cancel</a> 
    } 

Below is the action method where I have added [ValidateAntiForgeryToken] attribute.
    [HttpPost] 
    [ValidateAntiForgeryToken] 
    public ActionResult Create(Product p) 
       { 
       ProductDBContext db = new ProductDBContext(); 
       if (ModelState.IsValid) 
       { 
          db.Products.Add(p); 
          db.SaveChanges(); 
          return RedirectToAction("Index"); 
       } 
       else 
       { 
          return View(); 
    } 
    } 

Summary
In this blog, I have explained Cross-Site Request Forgery(CSRF), its steps and what changes we need to do in MVC application to prevent CSRF attacks.



ASP.NET MVC 5 Hosting - HostForLIFE.eu :: Bootstrap Tab Strip in ASP.NET MVC

clock September 18, 2019 12:47 by author Peter

In this post, we will see how to render given below bootstrap Tab script in Asp.net MVC 5 view.

Here the number of tabs displayed in view would depend on count of members in the list.

1. Create ASP.NET MVC 5 project.
 
2. Define Member class as follows in “Member.cs” file
    public class Member 
    { 
    public int Id { get; set; } 
    public string Name { get; set; } 
    } 

3. Add view to create action method and pass a list of members from controller Action method to razor view file. i.e. “create.cshtml”
    public ActionResult Create() 
    { 
    List<Member> members = new List<Member>(); 
    members = GetMemberList(); 
    return View(members); 
    } 
    private List<Member> GetMemberList() 
    { 
    List<Member> members = new List<Member>(); 
    members.Add(new Member{ Name = "member1" }); 
    members.Add(new Member { Name = "member2" }); 
    members.Add(new Member { Name = "member3" }); 
    members.Add(new Member { Name = "member4" }); 
    members.Add(new Member { Name = "member5" }); 
    return members; 
    } 


4. Using CSS classes, we can create a tabscript in our “create.cshtml” as shown below:
    @model IEnumerable<Member> 
    <div class="container"> 
    @if (Model.ToList().Count > 0) 
    { 
    <ul class="nav nav-tabs" role="tablist"> 
    @{int i = 0; 
    foreach (var item in Model) 
    { 
    if (i == 0) 
    { 
    <li class="nav-item"> 
    <a class="nav-link active" data-toggle="tab" href="#@item.Name">@item.Name</a> 
    </li> 
    } 
    else 
    { 
    <li class="nav-item"> 
    <a class="nav-link" data-toggle="tab" href="#@item.Name">@item.Name</a> 
    </li> 
    } 
    i++; 
    } 
    } 
    </ul> 
    <div class="tab-content"> 
    @foreach (var item in Model) 
    { 
    <div id="@item.Name" class="container tab-pane active"> 
    <br> 
    <h3>@item.Name 's Tab Area </h3> 
    </div> 
    } 
    </div> 
    } 
    </div> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script> 
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script> 



ASP.NET MVC 5 Hosting - HostForLIFE.eu :: Friendly Errors In MVC 5

clock July 20, 2018 08:51 by author Peter

In this article, I will be explaining 3 different ways to handle exceptions and display a friendly error page to the end user. Friendly Error Pages are the pages that you design to show the end user when any kind of not handled exception happens in your application and your expected result is not achieved. So, instead of presenting your end user with technical information regarding the exception, you show him a friend page. Also, presenting your end user with technical information is not a security best practice.

So, let's see the three ways.

Method 1: Custom Exception Filter
Custom Exception Filter

It is a filter that is called every time an exception occurs in the applied methods.

Why would I use a custom exception filter?


Because with a custom exception filter, you can handle in a generic way every kind of exception thrown by your actions and/or controllers. You may use custom exception filters to log your exceptions.

Steps to achieve this:
Step 1

Create a new class named CustomExceptionFilter.
public class CustomExceptionFilter : FilterAttribute, IExceptionFilter   
{   
    public void OnException( ExceptionContext filterContext )   
    {   
        filterContext.Result = new RedirectResult( "Home/About" );   
        filterContext.ExceptionHandled = true;   
    }   
}   

What this custom exception does is to redirect to your About action in your Home Controller. Do not forget to set the ExceptionHandled equal to true; otherwise it will not take effect.

Step 2
Apply your custom exception filter to your controller/action.
public class HomeController : Controller 
{ 
    [CustomExceptionFilter] 
    public ActionResult Index() 
    { 
        throw new Exception(); 
        return View(); 
    } 
 
    public ActionResult About() 
    { 
        ViewBag.Message = "Your application thrown an exception"; 
 
        return View(); 
    } 
 
    public ActionResult Contact() 
    { 
        ViewBag.Message = "Your contact page."; 
        throw new Exception(); 
        return View(); 
    } 
} 


You can see that the exception filter is applied only to your Index Action so if you access your Contact action, you will be able to see the non-handled exception page.

Method 2: Web.Config configuration
Why would I handle an exception by web.config configuration?

It is easy to configure and useful when you do not need to log or work on the exception.

Steps to achieve this:

Step 1
Include this in your web.config inside the system.web tag.
<customErrors defaultRedirect="Error.cshtml" mode="On"></customErrors> 

Step 2
Update your Controller.
public class HomeController : Controller 
{ 
    [HandleError] 
    public ActionResult Index() 
    { 
        throw new Exception(); 
        return View(); 
    } 
 
    public ActionResult About() 
    { 
        ViewBag.Message = "Your application description page."; 
 
        return View(); 
    } 
 
    public ActionResult Contact() 
    { 
        ViewBag.Message = "Your contact page."; 
        throw new Exception();
        return View(); 
    } 
} 


Observation - Like the custom exception filter, you may choose if you want to handle the exceptions at the Controller or Action level. Also, here, the handled exception is applied only to your Index action, you may see the non-handled error in the Contact View.

Method 3: Global.Asax Application_error
What is the Application_error?

It is to override the global exception handler of the application.

Why would I handle an exception by global.asax Application_error?
You do not need to set the places that you would like to handle the errors like before where you had to set the actions and controllers to be handled. Here, every exception will hit and be handled.

Steps to Achieve this:

Step 1
Update  your global.asax.
protected void Application_Error( object sender, EventArgs e ) 
  { 
      Exception exception = Server.GetLastError(); 
      Server.ClearError(); 
      Response.Redirect( "/Home/About" ); 
  } 


Like the custom exception handlers, it is very important to ClearError() in the Server. What is done here is the redirection of non-handled exceptions to the About action in the Home Controller. Congratulation, you just learned three good ways of handling exceptions in your application and presenting friendly error pages to your end users.



ASP.NET MVC 5 Hosting - HostForLIFE.eu :: List Of Users With Roles In ASP.NET MVC Identity

clock July 13, 2018 11:21 by author Peter

In this article, we will learn how to list all users with Associated Roles in ASP.NET MVC 5 using Identity. ASP.NET MVC 5 does not come with an inbuilt feature to list users with associated roles by default. However ASP.NET MVC have inbuilt UserManager, SignManager and RoleManager to assist this.

We need this feature in each of our applications as users are to be maintained along with their associated roles. We can apply a number of ideas to do this. In this article, we will learn a very simple way to list users with their associated RoleName as in the figure below.

Step 1
Create a View Model as Users-in-Role_ViewModel
public class Users_in_Role_ViewModel 
    { 
        public string UserId { get; set; } 
        public string Username { get; set; } 
        public string Email { get; set; } 
        public string Role { get; set; } 
    } 


Step 2
Add a new method called UsersWithRoles inside ManageUsersController and add the following codes.
public ActionResult UsersWithRoles() 
        { 
            var usersWithRoles = (from user in context.Users 
                                  select new 
                                  { 
                                      UserId = user.Id,                                       
                                      Username = user.UserName, 
                                      Email = user.Email, 
                                      RoleNames = (from userRole in user.Roles 
                                                   join role in context.Roles on userRole.RoleId  
                                                   equals role.Id 
                                                   select role.Name).ToList() 
                                  }).ToList().Select(p => new Users_in_Role_ViewModel() 
  
                                  { 
                                      UserId = p.UserId, 
                                      Username = p.Username, 
                                      Email = p.Email, 
                                      Role = string.Join(",", p.RoleNames) 
                                  }); 
  
  
            return View(usersWithRoles); 
        } 


Note - context.Users represents the table AspNetUsers which has navigation property roles which represent the AspNetUserInRoles table.

Step 3
Now, let’s add a View of UsersWithRoles method of ManageUsersController.
@model IEnumerable<MVC5Demo.UI.ViewModels.Users_in_Role_ViewModel> 
@{ 
    ViewBag.Title = "Users With Roles"; 
    Layout = "~/Views/Shared/_Layout.cshtml"; 
} 
  
<div class="panel panel-primary"> 
    <div class="panel-heading"> 
        <h3 class="box-title"> 
            <b>Users with Roles</b> 
        </h3> 
    </div> 
    <!-- /.box-header --> 
    <div class="panel-body"> 
        <table class="table table-hover table-bordered table-condensed" id="UsersWithRoles"> 
            <thead> 
                <tr> 
                    <td><b>Username</b></td> 
                    <td><b>Email</b></td> 
                    <td><b>Roles</b></td> 
                </tr> 
            </thead> 
            @foreach (var user in Model) 
            { 
                <tr> 
                    <td>@user.Username</td> 
                    <td>@user.Email</td> 
                    <td>@user.Role</td> 
                     
                </tr> 
            } 
        </table> 
    </div> 
  
    <div class="panel-footer"> 
        <p class="box-title"><b>Total Users till @String.Format("{0 : dddd, MMMM d, yyyy}", DateTime.Now)  : </b><span class="label label-primary">@Model.Count()</span></p> 
    </div> 
</div> 
  
  
@section scripts{ 
    <script> 
        $(function () { 
            $('#UsersWithRoles').DataTable({ 
                "paging": true, 
                "lengthChange": true, 
                "searching": true, 
                "ordering": true, 
                "info": true, 
                "autoWidth": true 
            }); 
        }); 
    </script> 
} 

Now, the above method and View will return the users to their roles.

n



ASP.NET MVC Hosting - HostForLIFE.eu :: Using Ajax in MVC Application

clock June 21, 2016 00:16 by author Anthony

In asp.net web form application, if we need ajax service, we will need to create wcf services on server side to serve ajax calls, while in MVC web application, no wcf is needed, a controller will do.

Here are two examples (GET and POST) of how to use ajax in mvc application

Http Get example: ajax consumer in view

<script type="text/javascript">
  var user = {
                'id': 1
            };
    $.get(
                'home/getUser',
                user,
                function (data) {
                    alert(data.name);
                }
    );
</script>


Http Get example: ajax server in home controller

public class HomeController : Controller
{
    // data GET service
     public JsonResult getUser(int id)
     {
            User user = db.Users.where(u=>u.id==id)
            return Json(user,JsonRequestBehavior.AllowGet);     }
}

A few points:


Controller must return JsonResult rather than ActionResult as a normal controller does as we would want the data to be returnd as json data, and it does not have a ‘d’ wrapper

JsonRequestBehavior.AllowGet must be set in Json()call, otherwise you will get:

500 internal server error with message like

This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet

You only need to set this parameter for GET and returning JSON array to avoid JSON hijacking, no need for POST requests.
Http POST example: ajax consumer in view


<script type="text/javascript">
var user={
            'name':’TheUser’,
            'age':30
        };
 $.post(
            'home/SaveUser',
            user,
            function (data) {
                if (data === true) {
                   alert('User is saved');
                }
                else {

                    alert('Failed to save the user');
                }
            },
            'json'
        );
</script>


Http POST example: ajax server in home controller

public class HomeController : Controller
{
    // data POST service
  [AcceptVerbs(HttpVerbs.Post)]
   public JsonResult SaveUser (string name, int age)
   {
        return Json(true);    }
}

A few points:

Have to decorate the controller with ‘POST’

Datatype in $.post in example is set to json, but it is not necessary to be so, if you just pass data in fields rather than in complex object. When it is not set to json it will use application/x-www-form-urlencoded as a way to pass data in standard post.


Summary:
In asp.net MVC you can use controller as ajax server without having to use wcf, compared with wcf, no configuration is needed

 

HostForLIFE.eu ASP.NET MVC Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



ASP.NET MVC Hosting - HostForLIFE.eu :: Configuring ELMAH In ASP.NET MVC

clock June 13, 2016 21:35 by author Anthony

In this article, I will integrate and setup ELMAH to asp.net MVC project. I will finish whole article in 5 different steps. ELMAH stands for Error Logging Modules and Handlers providing application wide error logging facilities. ELMAH is pluggable and easy to implement without changing single line of code. ELMAH work as interceptor of unhandled dotnet exceptions, that display over yellow screen of death. As per Author you can dynamically add ELMAH on running asp.net application without recompile or re-deploy whole application.You can download ELMAH binaries from google code or if you are using nuget then visit ELMAH nuget page.

Install

The best way to install any module to Asp.net MVC project is to use Nuget package Console. You can visit ELMAH nuget page for get latest version command.

Configure

After installing ELMAH , it will automatically update Web.Config file. If it's not so you can add following code to Web.Config file.

<configuration>
<configSections>
    <sectionGroup name="elmah">
      <section name="security" requirePermission="false" type="Elmah.SecuritySectionHandler, Elmah" />
      <section name="errorLog" requirePermission="false" type="Elmah.ErrorLogSectionHandler, Elmah" />
      <section name="errorMail" requirePermission="false" type="Elmah.ErrorMailSectionHandler, Elmah" />
      <section name="errorFilter" requirePermission="false" type="Elmah.ErrorFilterSectionHandler, Elmah" />
    </sectionGroup>
</configSections>

<system.web>   
    <httpModules>
      <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" />
      <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" />
      <add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" />
    </httpModules>
</system.web>

<system.webServer>
<modules>
      <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" preCondition="managedHandler" />
      <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" preCondition="managedHandler" />
      <add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" preCondition="managedHandler" />
</modules>
</system.webServer>
<elmah>
    <security allowRemoteAccess="false" />
    <errorLog type="Elmah.SqlErrorLog, Elmah" connectionStringName="YourConnectionStringName" />
</elmah>
    <location path="elmah.axd" inheritInChildApplications="false">
    <system.web>
      <httpHandlers>
        <add verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" />
      </httpHandlers>
      <!--
      <authorization>
        <allow roles="admin" />
        <deny users="*" /> 
      </authorization>
      --> 
    </system.web>
    <system.webServer>
      <handlers>
        <add name="ELMAH" verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" preCondition="integratedMode" />
      </handlers>
    </system.webServer>
  </location>
</configuration>
Usage Now, It's time to use and test elmah for application. Generate exception in Home Controller
public ActionResult Index()
{
   throw new Exception("This is test Exception");
          
   return View();
}


after generating exception check your elmah like http://www.example.com/elmah.axd
Here is our output

integrate-elmah-in-aspnet-mvc

integrate elmah in asp. net mvc

Security

In addition ELMAH provides seamless security feature to prevent unauthorized access. Please read our next article to make your elmah secure.

Filtering

ELMAH identify and store exceptions in different category, you can make or edit ELMAH error screen with different filters which we will discuss in our next ELMAH series.

Notification

You can setup ELMAH email notification when any exception occurs. To unable notification option you must include below code

Add ErrorMail module
<httpModules>
    <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah"/>
</httpModules>


Add SMTP Setting
<system.net>
    <mailSettings>
        <smtp deliveryMethod="network">
            <network host="..." port="25" userName="..." password="..." />
        </smtp>
    </mailSettings>
</system.net>
 

or
<elmah>
<errorMail from="..." to="..."  async="true" smtpServer="..." smtpPort="25" userName="..." password="..." />
</elmah>

 

 


HostForLIFE.eu ASP.NET MVC Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.

 



ASP.NET MVC 5 Hosting - HostForLIFE.eu :: AngularJS Login Page in ASP.NET MVC 5

clock May 17, 2016 23:45 by author Anthony

In this tutorial i am going to explain about how to create a login page using Angular js in MVC 5 application. In this tutorial i used Simple form validation using angular(we will discuss about angular validation in detail in future post).And also a $http angular built in service.

$http: It is a angular JS built in service for communicating with remote servers.In Angular all communications (Request and response) between server and client are handled by services like $http.

Step 1: Create a Data table in Database

1.Here i used Local Database for Table creation (Sql Express).
2.Right click server explorer --> expand Database --> Right click on tables --> Click Add new table.
3.Create a table with  following columns if you want you can add more columns.
4.Here i created following table.

Step 2: Add ADO.NET Entity Data Model

1.Right click on Models --> Add --> New Item -->Select ADO.NET Entity Data Model(Under Data) --> name it -->Add --> select Add from Database (In Entity Data Model wizard) --> Next
2.Select Database --> give name for web.config.
3.Choose your Database objects(tables) and click finish.


Step 3: Add a Model Class to Solution

1.Right click Models --> Add --> Class and name it (I named it as UserModel.cs).
2.These Model objects are useful while we sending data from View to Controller.
3.We bind this Model properties with angular ngModel.(you will see in index.cshtml).
4.replace code with following code

namespace LoginUsingAngular.Models
{
    public class UserModel
    {
        public string Email { get; set; }
        public string Password { get; set; }
    }
}

Step 4: Add New Action Method in HomeController to Check User Data

1.This Action Method gets data from database based on user entered data in form.and returns that data in Json format to angular Controller.
2.Add code in HomeController
getLoginData():

public ActionResult getLoginData(UserModel obj)
        {
            DatabaseEntities db = new DatabaseEntities();
            var user = db.Users.Where(x => x.Email.Equals(obj.Email) && x.Password.Equals(obj.Password)).FirstOrDefault();
            return new JsonResult {Data=user,JsonRequestBehavior=JsonRequestBehavior.AllowGet };
        }

Step 5: Add angular controller for checking Login Form

1.Create angular module in  Module.js file.
(function () {
    var myApp = angular.module("myApp",[]);
})();

2.Now add another script file for angular controller and Factory method.
3.Right click on Scripts folder --> add LoginController.js
4.Replace code in LoginController.js file.

angular.module('myApp').controller('LoginController', function ($scope, LoginService) {
 
        //initilize user data object
        $scope.LoginData = {
            Email: '',
            Password:''
        }
        $scope.msg = "";
        $scope.Submited = false;
        $scope.IsLoggedIn = false;
        $scope.IsFormValid = false;
 
        //Check whether the form is valid or not using $watch
        $scope.$watch("myForm.$valid", function (TrueOrFalse) {
            $scope.IsFormValid = TrueOrFalse;   //returns true if form valid
        });
 
        $scope.LoginForm = function () {
            $scope.Submited = true;
            if ($scope.IsFormValid) {
                LoginService.getUserDetails($scope.UserModel).then(function (d) {
                    debugger;
                    if (d.data.Email != null) {
                        debugger;
                        $scope.IsLoggedIn = true;
                        $scope.msg = "You successfully Loggedin Mr/Ms " +d.data.FullName;
                    }
                    else {
                        alert("Invalid credentials buddy! try again");
                    }
                });
            }
        }
    })
    .factory("LoginService", function ($http) {
        //initilize factory object.
        var fact = {};
        fact.getUserDetails = function (d) {
            debugger;
            return $http({
                url: '/Home/getLoginData',
                method: 'POST',
                data:JSON.stringify(d),
                headers: { 'content-type': 'application/json' }
            });
        };
        return fact;
    });


4.Here,I validated form using $watch in above code.
5.I created a angular service LoginService that gets data from server controller (from HomeController.getLoginData() action).
6.LoginForm() method is initiated when user submits form using ngSubmit as angular attribute.


Step 6: Add View to display Login Form

1.Right click on Index action --> Add View --> add
2.Replace Index.cshtml view code with following code

@{
    ViewBag.Title = "Login Using Angular";
}
<h2>Login Using Angular</h2>

<div ng-controller="LoginController">
    <form name="myForm" novalidate ng-submit="LoginForm()">
        <div style="color:green">{{msg}}</div>
        <table ng-show="!IsLoggedIn" class="table table-horizontal">
            <tr>
                <td>Email/UserName :</td>
                <td>
                    <input type="email" ng-model="UserModel.Email" name="UserEmail" ng-class="Submited?'ng-dirty':''" required autofocus class="form-control"/>
                    <span style="color:red" ng-show="(myForm.UserEmail.$dirty || Submited ) && myForm.UserEmail.$error.required">Please enter Email</span>
                    <span style="color:red" ng-show="myForm.UserEmail.$error.email">Email is not valid</span>
                </td>
            </tr>
            <tr>
                <td>Password :</td>
                <td>
                    <input type="password" ng-model="UserModel.Password" name="UserPassword" ng-class="Submited?'ng-dirty':''" required autofocus class="form-control"/>
                    <span style="color:red" ng-show="(myForm.UserPassword.$dirty || Submited) && myForm.UserPassword.$error.required">Password Required</span>
                </td>
            </tr>
            <tr>
                <td></td>
                <td>
                    <input type="submit" value="submit" class="btn btn-success" />
                </td>
            </tr>
        </table>
    </form>
</div>
@section scripts{
    <script src="~/Scripts/LoginController.js"></script>
}

Add script reference at the end of Index.cshtml page.
Take a look at following things i used in above Index.cshtml view.

ng-Model: ngModel is a angular directive.it is used for two way binding data from view to controller and controller to view.In above example i used it to bind from data to angular controller.

ng-show: ngShow allows to display or hide elements based on the expression provided to ngShow attribute.

ng-submit:  ng-submit prevents the default action of form and binds angular function to onsubmit events. This is invoked when form is submitted.

$dirty: It is angular built in property. It will be true if user interacted with form other wise false.This is one of the angular validation property i used in above example.There are many validation properties in angular like $invalid,$submitted,$pristine,$valid and $error.We will learn about all these these properties in later tutorials.

 




ASP.NET MVC 5 Hosting - HostForLIFE.eu :: How To Create Area?

clock April 28, 2016 20:59 by author Anthony

Today, you will learn how to create Area in MVC 5. In MVC 5 (Visual Studio 2013), Area option can be found under ‘Add Scaffold’ dialog. In this post, I will take you through step by step to setup and running Area in MVC 5.


As you know MVC Architecture separates all the logics: model logic, business logic and presentation logic and provides a very clean and light weight application in total. One more good thing that I love is, it provides logical separation physically also. In physical logic separation controllers, models and views are kept in another folder on root with the help of Area. Areas provide a way to separate a large MVC Web Application into smaller functional groupings inside MVC Application and each group contains MVC Structure (Ex. Model, View and Controller folders). Area was introduced with MVC 2 release.

Assume, you are working on a MVC Project where you have a requirement  to develop various sections like account section, administrative section, support section, billing section and so on. Area is the best choice here, it will provide a strong physical structure as well as better code manageability. See how it looks like.

 


You can see every section has MVC Architecture Controller, Model, View (view will have a Shared folder where you can place your layouts, partial views etc) and an AreaRegistration (which contains RegisterArea method very similar to RegisterRoutes).

How to Create It

We are going to create CRUD views for Employee inside Area. We will take the advantage of EF Code First. Let’s walk through the simple steps. In Visual Studio 2012 IDE (MVC 4), we just right click on Project | Add | Area to create Area.

 

Step 1


Right click on Project and then select Add | Scaffold | MVC 5 Area.

Step 2

When we click on ‘Scaffold’ it opens a dialog where we need to select MVC 5 Area and hit on Add button, it will ask to enter area name, type ‘Admin’ and hit Add.
Do the same to add Area for Billing and Support, at the end we will have following structure.



 

Now once we are done with adding areas, go to next step.

Step 3


In above step we added three Areas, in each area we will find a class file areanameAreaRegistration.cs file, open this file, we will find following RegisterArea method inside class which inherits AreaRegistration class.

public override void RegisterArea(AreaRegistrationContext context)
{
    context.MapRoute(
        "Billing_default",
        "Admin/{controller}/{action}/{id}",
        new { action = "Index", id = UrlParameter.Optional }
    );
}


Look at this root closely, we will find this route begins with Admin and then controller, action and id (which is marked as optional).


We will find same thing in other Area also.

In total we have three areanameAreaRegistration.cs classes all inherits AreaRegistration class, and also a route defined for the Area. These routes should be registered inside Application_Start() method of Global.asax file, here is the code.

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}


Now, let’s go in next step where we will create CRUD views and see how it opens in browser.


Step 4


Once we have done with previous steps, just go ahead and add model, controller and views to see how area opens in browser. We could and anything we want but just to keep things simple I am going to create a CRUD in Admin Area for Employee, here is the model I will be using.

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
}

Now, create CRUD views and browse it.

Look at the URL in above image you will see the first segment ‘Admin’ is area name, second segment ‘Employee’ is controller, third segment ‘Details’ is action result and fourth segment ‘1’ is ID.


So, you can see how Area is working in MVC 5. There is no difference in ‘Area in MVC 4’ and ‘Area in MVC 5’, things are still same, the only change is the way Area added, that’s it.

 

HostForLIFE.eu ASP.NET MVC 5 Hosting
HostForLIFE.eu revolutionized hosting with Plesk Control Panel, a Web-based interface that provides customers with 24x7 access to their server and site configuration tools. Plesk completes requests in seconds. It is included free with each hosting account. Renowned for its comprehensive functionality - beyond other hosting control panels - and ease of use, Plesk Control Panel is available only to HostForLIFE's customers. They
offer a highly redundant, carrier-class architecture, designed around the needs of shared hosting customers.

http://aspnetmvceuropeanhosting.hostforlife.eu/image.axd?picture=2015%2f10%2fhostforlifebanner.png



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Month List

Tag cloud

Sign in