C# Programming: 2016

Monday, October 17, 2016

21. How to use where function in ASP.NET MVC LINQ

Sunday, October 16, 2016

Difference between Single or SingleOrDefault in ASP.NET MVC LINQ with Da...



Welcome to ASP.NET tutorial on Single or SingleOrDefault. The exact difference is described in the video.

Thursday, September 15, 2016

Pagination in ASP.NET MVC | Numbers Assigned to Pages with Next and Pre...

Welcome to ASP.NET MVC Tutorial on How to make Paging. We are going to create a paging with help of PagedList.

At first you need to install pagedlist.mvc from package manager console with this code.
install-package pagedlist.mvc



Other Code are as follows:

 using PagedList;

-----------------Home Controller code----- ------

 public ActionResult Index(int? page)

        {

            StudentContext Db = new StudentContext();//create object of context

            List<Student> students = new List<Student>();

            students = Db.Students.ToList();

            int pageSize = 3;

            int pageNumber = (page ?? 1);

             return View(students.ToPagedList(pageNumber, pageSize));

         

        }

--------------------------------------------------------

-------------View Code--------Index.cshtml---------------



@*@model IEnumerable<ASPtutorial.Models.Student>*@

@using PagedList.Mvc;

@model PagedList.IPagedList<ASPtutorial.Models.Student>



@{

    ViewBag.Title = "Index";

}



<h2>Index</h2>



<p>

    @Html.ActionLink("Create New", "Create")

</p>

<table class="table">

    <tr>

        <th>

           Student Name

        </th>

        <th>

       Address

        </th>

        <th>

            Phone

        </th>

        <th></th>

    </tr>



@foreach (var item in Model) {

    <tr>

        <td>

            @Html.DisplayFor(modelItem => item.sName)

        </td>

        <td>

            @Html.DisplayFor(modelItem => item.sAddress)

        </td>

        <td>

            @Html.DisplayFor(modelItem => item.sPhone)

        </td>

        <td>

            @Html.ActionLink("Edit", "Edit", new { id=item.sId }) |

            @Html.ActionLink("Details", "Details", new { id=item.sId }) |

            @Html.ActionLink("Delete", "Delete", new { id=item.sId })

        </td>

    </tr>

}



</table>

<br />

<div style="margin:5px;">

    Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of @Model.PageCount



    @Html.PagedListPager(Model, page => Url.Action("Index",

    new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }))

</div>



If you have still Doubt then watch this video to be more clear. For onlice classes contact in facebook.

fb.com/ythecoder



Tuesday, September 13, 2016

Difference Between Viewbag, ViewData and TempData in ASP.NET MVC | ASP Hero

Welcome to ASP.NET tutorial on Viewbag, ViewData and Tempdata.

Viewbag:

for sending data from controller to view, data destroys on redirection.

eg. ViewBag.message="something";



ViewData:

is also for sending data from controller to view, data destroys on redirection.

eg. ViewData["message"]="something";



TempData:

is also for sending data from controller to view, data does not destroys on redirection.

After one redirection data can be used and then data destroys.

eg. TempData["message"]="something";

For further details watch this video.
For online classes knock me at fb.com/ythecoder

Sunday, September 11, 2016

17.How to Make Session in ASP.NET MVC | Register, Login , Authentication...

Welcome to ASP.NET tutorial on How to make Session. please follow this video for solving your problem on session.

15. Authentication System in ASP.NET MVC | Register, Login , Authenticat...

Welcome to ASP.NET MVC Tutorial on how to make authentication system in asp.net mvc. The details are in this video.

15 How to make Login System in ASP.NET MVC | Register, Login , Authentic...

Welcome to ASP.NET MVC Tutorial on How to make Login System.
Just Put this code in home Controller.

  public ActionResult login()

        {

            return View();

        }



        [HttpPost]

        public ActionResult login(user user)

        {

            StudentContext db = new StudentContext();

         

            var userLoggedIn = db.users.SingleOrDefault(x => x.username == user.username && x.password == user.password);



            if (userLoggedIn != null)

            {

                ViewBag.message = "loggedin";

                ViewBag.triedOnce = "yes";

                return RedirectToAction("mainpage", "home",new { username= user.username });

            }

            else

            {

                ViewBag.triedOnce = "yes";

                return View();

            }





        }
And Paste this code in Home Folder's Login.cshtml

@model ASPtutorial.Models.user



@{

    ViewBag.Title = "login";

}



<h2>login</h2>



@using (Html.BeginForm())

{

    @Html.AntiForgeryToken()



    if (ViewBag.message == null && ViewBag.triedOnce == "yes")

    {

        <h4>Username or Password not matched, please log in again or register.@Html.ActionLink("Register", "Register")</h4>

    }



    <div class="form-horizontal">

        <h4>user</h4>

        <hr />

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        <div class="form-group">

            @Html.LabelFor(model => model.username, htmlAttributes: new { @class = "control-label col-md-2" })

            <div class="col-md-10">

                @Html.EditorFor(model => model.username, new { htmlAttributes = new { @class = "form-control" } })

                @Html.ValidationMessageFor(model => model.username, "", new { @class = "text-danger" })

            </div>

        </div>



        <div class="form-group">

            @Html.LabelFor(model => model.password, htmlAttributes: new { @class = "control-label col-md-2" })

            <div class="col-md-10">

                @Html.PasswordFor(model => model.password, new { htmlAttributes = new { @class = "form-control" } })

                @Html.ValidationMessageFor(model => model.password, "", new { @class = "text-danger" })

            </div>

        </div>



        <div class="form-group">

            <div class="col-md-offset-2 col-md-10">

                <input type="submit" value="Login" class="btn btn-default" />

            </div>

        </div>

    </div>

}



<div>

    @Html.ActionLink("Back to List", "Index")

</div>


For more questions or queries ask me on fb.com/ythecoder or you can watch this video too. If you are interested in online class then do contact me in affordable price. :)

14. Registration of User in ASP.NET MVC | Register, Login , Authenticati...

Welcome to ASP.NET MVC tutorial on how to make a user registration.

I believe in less talking and more doing lets move on to writing code.
Lets make a student class i.e a model in model folder.

[Table("Students")]

    public class Student

    {

        [Key]

        public int sId { get; set; }

        [DisplayName("Student Name")]  //for display name above line must be added

        public string sName { get; set; } //just storing student Id,name,address,phone

        [DisplayName("Student Address")]

        public string sAddress { get; set; }

        [DisplayName("Student Phone")]

        public string sPhone { get; set; }

    }

lets create a context in model folder. I have given name student you can give anything you want

  public class StudentContext : DbContext

    {

   

        public DbSet<user> users { get; set; } //this line will get students info

    }



Put this code in home controller.

 public ActionResult register()

        {

            return View();

        }



Make respective view with scaffolding i.e register.cshtml with create template,student model, and studentContext or you can directly paste this code i dont mind :D


@model ASPtutorial.Models.user



@{

    ViewBag.Title = "register";

}



<h2>register</h2>



@using (Html.BeginForm())

{

    @Html.AntiForgeryToken()

   

    if(ViewBag.message!=null)

    {

        <h1>@ViewBag.message</h1>

    }



    <div class="form-horizontal">

        <h4>user</h4>

        <hr />

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        <div class="form-group">

            @Html.LabelFor(model => model.username, htmlAttributes: new { @class = "control-label col-md-2" })

            <div class="col-md-10">

                @Html.EditorFor(model => model.username, new { htmlAttributes = new { @class = "form-control" } })

                @Html.ValidationMessageFor(model => model.username, "", new { @class = "text-danger" })

            </div>

        </div>



        <div class="form-group">

            @Html.LabelFor(model => model.password, htmlAttributes: new { @class = "control-label col-md-2" })

            <div class="col-md-10">

                @Html.EditorFor(model => model.password, new { htmlAttributes = new { @class = "form-control" } })

                @Html.ValidationMessageFor(model => model.password, "", new { @class = "text-danger" })

            </div>

        </div>



        <div class="form-group">

            <div class="col-md-offset-2 col-md-10">

                <input type="submit" value="Create" class="btn btn-default" />

            </div>

        </div>

    </div>

}



<div>

    @Html.ActionLink("Back to List", "Index")

</div>


Again in home controller put this code.
 [HttpPost]
        public ActionResult register(user user)
        {
            StudentContext db = new StudentContext();
            db.users.Add(user);
            db.SaveChanges();

            ViewBag.message = "You are successfully registered";

            return View();
        }
For futher description of each code you can watch this video too. :)




Thursday, September 8, 2016

Wednesday, September 7, 2016

Tuesday, September 6, 2016

Wednesday, August 24, 2016

6. How To Use AJAX in ASP. NET MVC C# | Jquery | AJAX | ASPHero

Welcome to next tutorial on HOW TO USE AJAX IN ASP.NET MVC. At first open up index.chtml of Views/Home/index.cshtml .We will make a ajax call to retrive a square of supplied number dynamically without reloading the wholwe page. Now write the following code :

@*Welcome to asp.net mvc tutorial about uploading images*@

@*Now we are in Views/Home/index.cshtml*@

@*at first lets include a jquery file for ajax which is already provided by

    asp.net mvc as default*@

<script src="~/Scripts/jquery-1.10.2.js"></script>

@*otherwise you can download latest from jquery.com*@



<div style="margin:5px;">

<span>Supply a number to get square of it using AJAX</span>

    <br />

    <input type="number" id="supplied_number"/>

    <br /><br />

    <input type="button" value="Show" id="show_button"/>

    <br /><br />

    <div id="updating_div">Result</div>



</div>



@*lets write our script for ajax call*@



<script>

    $(document).ready(function () {

        $("#show_button").click(function () {

            sNumber = $("#supplied_number").val();

            $.ajax({

                type:"post",

                url: "/Home/square",

                data: { number: sNumber },

                success: function (data) {

                    $("#updating_div").html("Result : " + data.result);

                }

               

            });

        });

    });

   

</script>

@*now lets move to controller action*@


Now we need to make a function in controller action to return square number in json format.
 public ActionResult square(int number) //parameter must be same as supplied
        {
            int squaredResult = number * number;
            return Json(new { result = squaredResult }, JsonRequestBehavior.AllowGet);
            //thats it to finish our job :) lets run
        }
That's enough to make a ajax call. In return controller action is returning result in json form which is displayed in updating div.Hope you guys learn the concept. Stay tuned for more tutorials, to be more clear you can watch this video too. Thanks :)


Tuesday, August 23, 2016

Multiple Files Upload in ASP.NET MVC C#

You are at correct place to give a good start on ASP.NET MVC. Here i am going to show you how to upload multiple files in asp.net mvc.here we go.
Design code in view:

@*Welcome to asp.net mvc tutorial about uploading images*@

@*Now we are in Views/Home/index.cshtml*@



@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))

{

    <h3>Upload Image</h3>

    <input multiple type="file" name="files" value="Browse"/>

    <br />

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

}



@if(ViewBag.UploadSuccess==true)

{

    <span>Upload Completed Successfully</span>

}



Controller code in HomeController.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using ASPtutorial.Models; //your projectName.Models

using System.IO;



namespace ASPtutorial.Controllers

{

    public class HomeController : Controller

    {

        public ActionResult Index()

        {

            return View();

        }



        [HttpPost] //must be post method

        public ActionResult Index(List<HttpPostedFileBase> files) //take files as a list

        {

            var path = "";  //for path to save

            foreach(var item in files)  //iterate in each file

            {

                if (item != null)   //check file is null or not

                {

                    if (item.ContentLength > 0) //check length of bytes are greater then zero or not

                    {

                        //for checking uploaded file is image or not

                        if (Path.GetExtension(item.FileName).ToLower() == ".jpg"

                            || Path.GetExtension(item.FileName).ToLower() == ".png"

                          || Path.GetExtension(item.FileName).ToLower() == ".gif"

                            || Path.GetExtension(item.FileName).ToLower() == ".jpeg")

                        {

                            path = Path.Combine(Server.MapPath("~/Content/Images"), item.FileName);

                            item.SaveAs(path);

                            ViewBag.UploadSuccess = true;

                        }

                    }

                }

            }

         

            return View();

        }



    }

}



That's it for multiple file upload , if you wanna see the code in video the watch this,Ok Good luck :)



Monday, August 22, 2016

4. How To Upload Image In ASP NET MVC

Welcome to tutorial on HOW TO UPLOAD IMAGE IN ASP.NET MVC. Here we go, At first write following line of code in Views/Home/Index.cshtml

@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <h3>Upload Image</h3>

    <input type="file" name="file" value="Browse"/>

    <br />

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

}

@if(ViewBag.UploadSuccess==true)

{
    <span>Upload Completed Successfully</span>
}
Here using statement is used to create a form with help of html helper. Form Submission method is post method. Other type of methods are get,put,delete etc. Important thing to notice while uploading is enctype attribute, here enctype attribute is set to multipart form data. Now use input of type file for uploading file using it. Place a uploading button which actually submits the form to Index actionResult method of Home Controller.

Now in HomeController.cs place the following code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using YourProjectName.Models;
using System.IO; //for file operation

namespace YourProjectName.Controllers

{
    public class HomeController : Controller

    {

        public ActionResult Index()

        {

            return View();

        }

        [HttpPost]

        public ActionResult Index(HttpPostedFileBase file)

        {

            var path = "";

            if(file!=null)

            {

                if(file.ContentLength>0)

                {

                    //for checking uploaded file is image or not

                    if(Path.GetExtension(file.FileName).ToLower()==".jpg"

                        || Path.GetExtension(file.FileName).ToLower() == ".png"

                      || Path.GetExtension(file.FileName).ToLower() == ".gif"

                        || Path.GetExtension(file.FileName).ToLower() == ".jpeg")

                        {

                        path = Path.Combine(Server.MapPath("~/Content/Images"), file.FileName);

                        file.SaveAs(path);

                        ViewBag.UploadSuccess = true;

                    }

                }

            }

            return View();

        }

    }

}

Here HttppostedFileBase is a datatype to accept the file submitted from the form. At first file is checked it is null or not. If not null  that is some file is uploaded then file length is checked if file length is greater then zero then we proceed. Now we check the file extention matches the file format of image or not like jpg,png,gif etc and then if it matches. Now we combine server folder path to upload and the filename together and finally save it with file.saveAs function. ViewBag is used to detect whether image file was successfully uploaded or not. Finally return view to show image is uploded. That's all for uploading image in ASP.NET MVC. Hope you guys understand better, if you have still any doubt then you can watch this video too. Thanks and do subscribe :)

Sunday, August 21, 2016

Adding Two Numbers In ASP.NET MVC | ASPHero

Welcome to the tutorial on HOW TO ADD TWO NUMBERS IN ASP.NET MVC C#.
You are at absolutely correct page to give a good start.
Now Lets start our job. At first Create a model in Models folder named addmodel.cs.
Add > class . addmodel.cs
// code:
public class addmodel

    {

        public int firstNum { get; set; } //for first number

        public int secondNum { get; set; } //for second number

        public int result { get; set; }  //for storing result after addition

    }

Now we are going to add a actionResult Method in Home Controller

Use a using
//code:
using YourProjectName.Models;


       [HttpPost] //this is required for post type of submit

       public ActionResult Index(addmodel am) //for this you have to add a using

        {

            am.result = am.firstNum + am.secondNum;

            return View(am); //sending result to view so that we can see it :)

        }

Now time to show output in a page.
Write this code in Views/Home/index.cshtml


@*Code: *@


@model YourProjectName.Models.addmodel


 @using (Html.BeginForm("Index", "Home", FormMethod.Post))

    {

        <br />

        @Html.EditorFor(m=>m.firstNum)

        <br /><br />

        @Html.EditorFor(m=>m.secondNum)

        <br /><br />

        @Html.DisplayFor(m=>m.result)

        <br /><br />

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

    }


Now you are ready to go.Just Run The project. If you are still confused then watch this video. And Don't forget to subscribe for more similar kind of stuff. Good luck :)



Saturday, August 20, 2016

2. Displaying Images in ASP NET MVC | ASPHero

Welcome to the tutorial on HOW TO DISPLAY IMAGE IN ASP.NET MVC. You are at right place to move ahead.
Sometimes in life we feel difficulties with small things too, if we can't solve that we can't move ahead, similarly this is the thing here, it is also a pretty easy way to do, but at first we all get difficulties, here the solution for displaying images in asp.net mvc.



At first Add a image file in Content folder.

Right click on Content > Add > Existing Item> choose image> OK



HTML Code in file Home/index.cshtml

<img src="@Url.Content("~/Content/imagename.png")" width="500" height="500" />



Its that much easy, Good luck and keep going, I m always with you :)
Further You can watch this video too.



Thursday, August 18, 2016

How to make DropDownList in ASP.NET MVC

Welcome to asp.net Tutorial on how to make dropdown list in asp.net mvc. You are at absolutely right place to start. Lets move on to see how to solve it.
 We are making dropdownlist in a View. i.e Home/Index.cshtml
At first create a SelectListItem

@{ 

    List<SelectListItem> daysList = new List<SelectListItem>();

    daysList.Add(new SelectListItem { Text = "Sunday", Value = "0"});

    daysList.Add(new SelectListItem { Text = "Monday", Value = "1" });

    daysList.Add(new SelectListItem { Text = "Tuesday", Value = "2"});

    daysList.Add(new SelectListItem { Text = "Wednesday", Value = "0" });

    daysList.Add(new SelectListItem { Text = "Thursday", Value = "0"});

    daysList.Add(new SelectListItem { Text = "Friday", Value = "0"});

    daysList.Add(new SelectListItem { Text = "Saturday", Value = "0" });


}

Here we are creating list of days to display it in dropdown list. If you like to select sunday as default then use this code.
daysList.Add(new SelectListItem { Text = "Sunday", Value = "0",selected=true});

You can give any text or value as you like, whichever you need later. Now Let's create DropDownList in our page.
<h1>Select Day</h1>
@Html.DropDownList("Days", daysList, "Select Day")

This Completes our task on making dropdownlist. If you are still confused then you can watch this video too. Thanks.





Sunday, August 14, 2016

How To Make Money By Just Watching Youtube Videos

Welcome to new tutorial on HOW TO MAKE MONEY BY JUST WTCHING YOUTUBE VIDEOS.

For this you have to go to www.paid2youtube.com. Register there with your name and email. Select your country. If you face money withdrawing problems in your country from paypal then you can choose that country which accepts paypal. After creating account you will get a confirmation email, just open that email and verify your account. Now you are all set to go for earning from paid2youtube. Just open paid2youtube.com , login there with username , password and a captcha given there. After that you will see the list of videos which you can click to view. For security purpose you are asked to chose colours from boxes just choose correct color. And then you will see videos.some are of 1 minutes or some are of 10 seconds, according to that you will generate the revenue and you will start earning instantly, this process may be slow but its a genuine method, making money was never easy. Ok guys best of luck see you later :)

Tuesday, January 12, 2016

ASP.NET MVC Database Tutorial on CRUD's Update

Welcome to Another tutorial on ASP.net MVC Database CRUD's Update tutorial.
Lets start without any delay.
At first Create a UC user Context in top of class.
 private userContext UC = new userContext();

Now make an ActionResult method as follows:

 [HttpGet]
        public ActionResult update(string username)  //passing username to change
        {
            user usr = UC.users.SingleOrDefault(u => u.username == username); //bringing a row to //change
            usr.username = "John";  //changing old username to 'john'
            UC.SubmitChanges();    //confirming change...


            return RedirectToAction("users", "Home");       //After updating user return view of users list
        }

Above piece of code will easily allow you to update the user. By knowing these basics you can make your own advanced form of code with some HTML form type of work in HttpPost also.GoodLuck.

If you want to learn more on User context and how that UC is working then you can watch this video too for more clear understanding.

Saturday, January 9, 2016

Javascript Function in very easy way

Welcome to another Javascript Tutorial on Function. Function is just a bunch of codes given a name.
Lets start making a function in this tutorial. Write following line of code in notepad or any editor and save as dot html (myfunction.html).

<html>
<head>
<title>Script in head section</title>
<script type="text/javascript">      
function message()               
{
alert("This alert box was called with the onload event"); 
}
</script>
</head>

<body onLoad="message()">      


</body>
</html>

Here script tag start our javascript.
function keyword is use to make function. Here message is our function.
alert is another pre built function to show message.
Message Function will execute upon a page load.
Now start that file with any browser and see the magic :)

You can watch following video for above stuff.

Tuesday, January 5, 2016

ASP.NET MVC Full Database Tutorial

Welcome to Database tutorial on Microsoft ASP.net MVC web app. You are at perfect place to give a jumpstart on asp mvc database.

Lets Start our Journey.

Lets Create Database First.
 Just goto Appdata folder and create a database and click on create new table.
The table definition is below:

CREATE TABLE [dbo].[users] (
    [Id]          INT            IDENTITY (1, 1) NOT NULL,
    [username]   NVARCHAR (MAX) NOT NULL,
    [password]   NVARCHAR (MAX) NOT NULL,
    [email]      NVARCHAR (MAX) NOT NULL,

    CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([Id] ASC)
);

Here PK means primary key in our users table .

Lets Create our Model.
Model means just a class.

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

namespace mvc.Models
{
    [Table(Name = "users")]
    public class user
    {
        [Column(IsPrimaryKey = true, IsDbGenerated = true)]
        public int Id;
        [Column]
        public string username;
        [Column]
        public string password;
        [Column]
        public string email;
     


    }
}

//----To remove red lines just add a sqlite reference from references-------------------------

Lets Create A Context of user:
Context means just a easy way to connect with database table related with our user class here.
//-------context-----------------------
using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Linq;
using System.Web;

namespace mvc.Models
{
    public class userContext : DataContext
    {
       // for local
        private const String ConnectionString = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|mydatabase.mdf;Integrated Security=True";
//for server:
 // Data source will be different check in your connection string in server

        public userContext()
            : base(ConnectionString)
        {
        }

        public Table<user> users;

    }
}

//----------------------------------------


View and Controller:
To show view and controller will be very bulky here because must of the codes are already given with the default asp mvc framework. So i suggest you to watch this video for full scenario. It is a complete tutorial on asp.net mvc web app with database.

The first of Databse Tutorial is here.



The second Video is here.

Ok guys you are now able to make a users list fetching data from databse table in asp mvc.
For further tutorials stay tuned. For javascript tutorial, you can visit my javascript blog:
https://javascripthero.blogspot.com