MVC(MODEL-VIEW-CONTROLLER)

 *********MVC(MODEL-VIEW-CONTROLLER)**********

Introduction


1.MVC is model view controller structure

2.It provide the layer architecturein dot net application

3.MVC is provide 4 specific component

   i]dot net framework

   ii]asp.net mvc

   iii] webform

   iv]IIS

4.mvc code is to be relies by mspl(microsoft public licence)

5.mvc is manage complexity of application

6.mvc provide light weight application

7.provide more interactive and responsive application

8.mvc is provide tdd(test driven development)



*****WHAT IS MVC PATTERN*****

a model view controller design pattern is prefer c,c++,java and c#

mvc(model view editor previously)


****MVC Architecture*****

model:-inside the model create only class

view:-only used design section(UI) and work with html.extention:-.cshtml

controller:-(coading)it handle communication from the user overall application(logic building).controller manage http url



*****MVC Lifecycle*****


application lifecycle:-work with application start and application end


request lifecycle:-it is sequence of event that hppen every time and http request is handle by an application


****MVC Folder structure****

1.model-class and variable

2.controller-logic

3.view-design(.cshtml)

4.appdata-database

5.appcode-class and object



****What is controller*****

1.using AddController option create a controller

2.controller reference :-using system.web.mvc.controller

3.all conttroller is empty newly create

4.all controller name specified Controller keyword


structure of controller

http://localhost/controller name/function name


****how to pass parameter in a controller****


using ? operator


http://localhost/home/index?a=10


HOW TO CREATE FIRST MVC APPLICATION


step 1:file menu-> new project->visual c#->web->select asp.net web application->select folder->ok->mvc

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



HOW TO CREATE MODEL

1.create only class

2.all class reserve specific attribute(variable)

3.all variable declare public specifier

4.all variable is used to get set attribute 


step 1:-go to the solution explorer

step 2:-right click on model folder->add class


all model variable is used to get set property.


EXAMPLE:


using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;


namespace WebApplication1.Models

{

    public class student

    {

        public int stuid { get; set; }

        public string stuname { get; set; }

    }

}


HOW TO CREATE CONTROLLER

all controller name is represent with controller keyword

right click on controller->add->controller->mvc 5 controller empty


ACTION RESULT

1.default method

2.it return output to view page

3.it communicate with http


note:if controller is used to return any types of information direct to web browser in this case using string type index method.

controller direct communicate to http local host


ActionResult represent the event in mvc application

http://localhost:64580/student


http://localhost:64580/controller_name 


HOW TO CREATE VIEW

all view is to be created with the help of controller method

before designing a view create controller and model(class)

view can create cs code or html code   

step 1:-open controller->right click on controller function(eg.Index())->add view


view name :-automatic as per function name(bydefault)

template:-data representation format(as per user choice)

model class:-select your class as per class name

set layout(shared layout):-view->shared->layout


INTEGRATION OF MODEL VIEW AND CONTROLLER

***HOW TO ACCESS REFERENCE model to controller***

using folder name(root).models;


using WebApplication1.models;



using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using WebApplication1.Models;


namespace WebApplication1.Controllers

{

    public class studentController : Controller

    {

        static IList<student> stulist = new List<student>

        {

            new student()

            {

                     

                studid=1,

                studname="ramesh",

                age=20

            },

            new student()

            {

                studid=2,

                studname="suresh",

                age=22

            },

            new student()

            {

                studid=3,

                studname="radha",

                age=25

            },

            new student()

            {

                studid=4,

                studname="riya",

                age=30

            }


        };


        // GET: student

        

        public ActionResult Index()

        {

            return View(stulist);//list object

        }


        public ActionResult Edit(int id)

        {

            var std = stulist.Where(s => s.studid == id).FirstOrDefault();

            return View(std);

        }

    }

}




Controller Action and parameters


In MVC provide the special facility for creating a user function inside the controller 

http://localhost:52395/student/welcome

syntax:    /controller/function name




using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;


namespace WebApplication1.Controllers

{

    public class studentController : Controller

    {

        // GET: student

        public ActionResult Index()

        {

            return View();

        }

        public string welcome()

        {

            return "welcome to my website";

        }

    }

}




***HOW TO CREATE PARAMETER INSIDE THE CONTROLLER FUNCTION***

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;


namespace WebApplication1.Controllers

{

    public class studentController : Controller

    {

        // GET: student

        public ActionResult Index()

        {

            return View();

        }

        public string welcome(string data)

        {

            return "welcome to my website "+ data;

        }

    }

}



****MVC Action Selecter***

Action selecter are attribute that are applied on action method of a controller.

All action selecter is used to action name method.

syntax: [ActionName("name")]

All action parameter create inside the controller 


HOW TO CREATE VIEW PAGE IN ACTIONNAME PARAMETER


right click on action name->add view


HOW TO RUN ACTION PARAMETER 

syntax:

localhost/controllername/actionname



**** MVC ViewData, ViewBag and TempData(most IMP)****


ViewData:- ViewData is a dictionary of object Drivied from viewdata Disnary

ViewData Store All information in a form of string

all program written inside 

@{


}



EXAMPLE:

Controller code:


using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;


namespace WebApplication1.Controllers

{

    public class studentController : Controller

    {

        // GET: student

        public ActionResult Index()

        {

            List<string> city = new List<string>();

            city.Add("nagpur");

            city.Add("puna");

            city.Add("bhopal");

            city.Add("mumbai");

            city.Add("amarawati");

            //create view data

            ViewData["cityname"] = city;


            return View();

        }

    }

}


HTML Code:


@model WebApplication1.Models.student


@{

    ViewBag.Title = "Index";

}


<h2>this is my viewdata example</h2>

<ol>

    @{ 

        foreach(var city1 in ViewData["cityname"] as List<string>)

        {

            <li>

                @city1

            </li>

        }

    }  


</ol>


****VIEWBAG****

it is similar to viewdata concept

viewbag cannot required any types of conversion

viewbag dynamically convert data


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


Tempt data

Tempt data is an other types of data dictionary.

Tempt data is used to transfer data between one page to another page

tempt data is similar to view data concept



HOW TO CREATE TEMPT DATA


TempData["variable"]=value;




****MVC RAZOR***(IMP)

1.Razor is used to viewdata concept

2.razor is general purpose templating engin. It used to html page

3.Razor is a combination of template + data = output

4.Razor is a light weight designing concept because is used to html page.

5.All type of Razor statement is used to @ symbol.


HOW TO CREATE RAZOR IN MVC


@model WebApplication1.Models.student


@{

    var msg = "my first razor program";

}


<h2>@msg</h2>


Example:

@model WebApplication1.Models.student


@{

    var date = DateTime.Now.ToShortDateString();

}


<h2>@date</h2>

<br />


<h1>

    today is @date

</h1>


**using <text> in razor syntax***

@model WebApplication1.Models.student


@{

    var date = DateTime.Now.ToShortDateString();


    <text>Today is </text>@date

}


****HOW TO USE IF CONDITION IN RAZOR***

@model WebApplication1.Models.student


@{

    if(DateTime.IsLeapYear(DateTime.Now.Year))

    {

        //@: use for message writting

        @DateTime.Now.Year @:Is leap year

    }

    else

    {


        @DateTime.Now.Year @: not a leap year

    }

}


NOTE:@ not required for if,for,while inside the programming block

         @{

               //code

           }

Example:

@model WebApplication1.Models.student


        @for(int i=1;i<=10;i++)

        {


            @i.ToString() <br />

        }


***switch case statement****

@model WebApplication1.Models.student


@{ 


    var value = 2;


}

<hr />

@switch(value)

{


    case 1:

        <p>you press 1</p>

        break;

    case 2:

        <p>you press 2</p>

        break;

    case 3:

        <p>you press 3</p>

        break;

    default:

        <p>invalid choice</p>

        break;

}


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



Razor helper classes


HTML helper class is used to mvc in html programming language


HOW TO CREATE RAZOR HELPER


example


CONTROLLER CODE:


using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;


namespace WebApplication1.Controllers

{

    public class studentController : Controller

    {

        // GET: student


            

        public ActionResult Index()

        {

            return View();

        }


        public ActionResult htmlhelperdemo()

        {


            return View();

            


        }

        [HttpPost]

        public ContentResult userregistration()

        {

            return Content

                (

                "user name="+Request.Form["username"]+"<br>"+

                "email id="+Request.Form["emailid"]+"<br>"+

                "contact="+Request.Form["contact"]+"<br>"



                );



        }

    }

}


HTML CODE:


@model WebApplication1.Models.student


@{

    Layout = null;

}


<!DOCTYPE html>


<html>


<body>


    @using (Html.BeginForm("userregistration", "student"))

    {


        @Html.Label("user name")

        <br />

        @Html.TextBox("username")

        <br />

        @Html.Label("email id")

        <br />

        @Html.TextBox("emailid")

        <br />

        @Html.Label("contact")

        <br />

        @Html.TextBox("contact")


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


    }

</body>

</html>

MVC Validation

1.all mvc validation implement inside the classes(model)
2.validation is used to AataAnnotations library inside component model 
3.all validation inside[ ]

Types of validation
1.[Required]-default message(name required)
How to write user meaasage in required validation
[Required(ErrorMessage ="city input compulsory")]
        public string city
        {

            get;set;
        }
Set the length of charecter
 [Required(ErrorMessage ="college name compulosory")]
        [StringLength(30)]
        public string college
        {

            get;set;
        }

How to set minimum length validation

[Required(ErrorMessage ="branch input compulosory")]
        [StringLength(30,MinimumLength =10,ErrorMessage ="min length required")]
        public string branch
        {

            get;set;
        }

How to set Regular expression validation
[Required(ErrorMessage ="mobile no required")]
        [RegularExpression(@"\d{10}",ErrorMessage ="invalid mobile no")]
        public string mobile
        {

            get;set;
        }

NOTE:@ is called as expression symbol

How to set range validator

[Required(ErrorMessage ="age compulsory")]
        [Range(25,35,ErrorMessage ="age between 25 to 35")]
        public int age
        {

            get;set;
        }

How to set range in date variable

[Required(ErrorMessage ="age compulsory")]
        [Range(25,35,ErrorMessage ="age between 25 to 35")]
        public int age
        {

            get;set;
        }

How to set min and max length

[Required(ErrorMessage ="address compulosry")]
        [MinLength(10,ErrorMessage ="min 10 required")]
        [MaxLength(50,ErrorMessage ="max 50 required")]
        public string address
        {

            get;set;
        }
  
Postal code validation
[Required(ErrorMessage ="postel code required")]
        [DataType(DataType.PostalCode,ErrorMessage ="invalid postelcode")]
        public string postelcode
        {

            get;set;
        }

URL Validation
 [Required(ErrorMessage ="weburl compulosry")]
        [DataType(DataType.Url,ErrorMessage ="invalid url")]
        public string weburl
        {

            get;set;
        }

Mobile no validation

[Required(ErrorMessage ="no compulosory")]
        [DataType(DataType.PhoneNumber,ErrorMessage ="invalid no")]
       public string mobile1
        {

            get;set;
        }

Password validation

[Required(ErrorMessage ="password compulosry")]
        [DataType(DataType.Password,ErrorMessage ="invalid password")]
        public string pass
        {

            get;set;
        }
**************complete example with all validations*************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace WebApplication1.Models
{
    public class employee
    {
        [Required]
        public string name
        {
            get;set;
        }
        [Required]
        public string lastname
        {
            get;set;
        }
        [Required(ErrorMessage ="city input compulsory")]
        public string city
        {

            get;set;
        }
        [Required(ErrorMessage ="college name compulosory")]
        [StringLength(30)]
        public string college
        {

            get;set;
        }
        [Required(ErrorMessage ="branch input compulosory")]
        [StringLength(30,MinimumLength =10,ErrorMessage ="min length required")]
        public string branch
        {

            get;set;
        }

        [Required(ErrorMessage ="mobile no required")]
        [RegularExpression(@"\d{10}",ErrorMessage ="invalid mobile no")]
        public string mobile
        {

            get;set;
        }
        [Required(ErrorMessage ="age compulsory")]
        [Range(25,35,ErrorMessage ="age between 25 to 35")]
        public int age
        {

            get;set;
        }
        [Required(ErrorMessage ="date compulosry")]
        [Range(typeof(DateTime),"01-01-2023","02-02-2023",ErrorMessage ="date inpput correct format")]
        public DateTime dob
        {

            get;set;
        }
        [Required(ErrorMessage ="address compulosry")]
        [MinLength(10,ErrorMessage ="min 10 required")]
        [MaxLength(50,ErrorMessage ="max 50 required")]
        public string address
        {

            get;set;
        }
        
        [Required(ErrorMessage ="no compulosory")]
        [DataType(DataType.PhoneNumber,ErrorMessage ="invalid no")]
       public string mobile1
        {

            get;set;
        }

        [Required(ErrorMessage ="password compulosry")]
        [DataType(DataType.Password,ErrorMessage ="invalid password")]
        public string pass
        {

            get;set;
        }


        }
    }


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

HOW TO CREATE AREA IN MVC


area is a special type of concept for creating folder structure in mvc application 

how to create area
right click on root->add->area

how to execute area in mvc

syntax: areaname/controller/page
eg.Admin/Admincon/Index

*****how to insert data entry in database mvc using control******

Example:

model code

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

namespace WebApplication1.Models
{
    public class customer
    {
        public int EID
        {
            get;set;
        }
        public string NAME
        {

            get;set;
        }

        public string CITY

        {
            get;set;
        }
    }
}


Controller code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.SqlClient;
using WebApplication1.Models;

namespace WebApplication1.Controllers
{
    public class customerController : Controller
    {
        // GET: customer

        SqlConnection cn;
        SqlCommand cm;
        SqlDataReader dr;
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Index(customer c1)
        {
            //create database code

            string cs = @"Data Source=IP; 
    Network Library=Library; 
    Connection Timeout=15; 
    Packet Size=4096; 
    Integrated Security=no; 
    Initial Catalog=ID; 
    User ID=ID; 
    Password=PW; 
    Encrypt=no; 
    Max Pool Size=5000;";
            cn = new SqlConnection(cs);
            cn.Open();

            string k = "insert into mvc_emp(eid,name,city)values(@eid1,@name1,@city1)";
            cm = new SqlCommand(k, cn);
            cm.Parameters.AddWithValue("eid1", c1.EID);
            cm.Parameters.AddWithValue("name1", c1.NAME);
            cm.Parameters.AddWithValue("city1", c1.CITY);
            cm.ExecuteNonQuery();
            return View(c1);//pass class object
        }
    }
}


view code:

@model WebApplication1.Models.customer

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    
    <font color="red">Customer registration form</font><br />
    @using (Html.BeginForm("Index", "customer", FormMethod.Post))
    {
        <p>enter customer id</p><br />
        @Html.TextBoxFor(m => m.EID)<br />

        <p>enter customer name</p><br />
        @Html.TextBoxFor(m => m.NAME)<br />
        <p>enter customer city</p><br />
        @Html.TextBoxFor(m => m.CITY)<br />

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

    }
</body>
</html>



  













Comments

Popular posts from this blog

C# console applications

DATATABLES