Hands on Lab Mvc

Embed Size (px)

Citation preview

  • 7/23/2019 Hands on Lab Mvc

    1/15

    generating hyperlinks using actionlink html helper, for

    navigation between MVC pages.

    We want to display all the employees in a bulletted listas shown below. Notice that all the

    employee names are rendered as hyperlinks.

    When the hyperlink is clicked, the user will be redirected to employee details page,

    displaying the full details of the employee as shown below.

    Copy and paste the following Index() action method in mployeeControllerclass. This

    method retrieves the list of employees, which is then passed on to the view for rendering.

    publicActionesult !nde"()

    #

    $mployeeConte"t employeeConte"t % new$mployeeConte"t()&

    'ist$mployee employees % employeeConte"t.$mployees.To'ist()&

    return *iew(employees)&

    +

    At the moment, we don!t have a viewthat can display the list of employees. To add the

    view

    ".ight clic on the !nde"() action method

    #.-et

    *iew name % Index

    *iew engine % $a%or

    -elect, Create a stronlgy&typed view checkbox

  • 7/23/2019 Hands on Lab Mvc

    2/15

    -elect 'mployee'from 'Model class'dropdownlist

    (.Clic Add

    At this point, 'Index.cshtml'view should be generated. Copy and paste the following code

    in !nde".cshtml.

    /model !$numerable0*C1emo.0odels.$mployee

    /using 0*C1emo.0odels&

    divstyle%font2family3Arial

    /#

    *iew4ag.Title % $mployee 'ist&

    +

    h5$mployee 'ist6h5

    ul

    /foreach ($mployee employee in /0odel)#

    li/7tml.Action'in(employee.Name, 1etails, new # id % employee.$mployee!d +)6li

    +

    6ul

    6div

    )oints to $emember*

    "./model is set to !$numerable0*C1emo.0odels.$mployee

    #.We are using 7tml.Action'in html helper to generate lins

    Copy and paste the following code in +etails.cshtml/7tml.Action'in(4ac to 'ist, !nde")

    will discuss working with # related tables in MVC".tbl1epartment

    #.tbl$mployee

    se the s-l script to create and populate these # tables

    Create tabletbl1epartment(

    !d int primary ey identity,

    Name nvarchar(89)

    )

    !nsert intotbl1epartment values(:!T:)

    !nsert intotbl1epartment values(:7:)

  • 7/23/2019 Hands on Lab Mvc

    3/15

    !nsert intotbl1epartment values(:;ayroll:)

    Create tabletbl$mployee

    (

    $mployee!d int ;rimary ender nvarchar(=9),

    City nvarchar(89),

    1epartment!d int

    )

    Alter tabletbl$mployee

    add foreign ey(1epartment!d)

    references tbl1epartment(!d)

    !nsert intotbl$mployee values(:0ar:,:0ale:,:'ondon:,=)

    !nsert intotbl$mployee values(:?ohn:,:0ale:,:Chennai:,@)!nsert intotbl$mployee values(:0ary:,:emale:,:New Bor:,@)

    !nsert intotbl$mployee values(:0ie:,:0ale:,:-ydeny:,5)

    !nsert intotbl$mployee values(:-cott:,:0ale:,:'ondon:,=)

    !nsert intotbl$mployee values(:;am:,:emale:,:alls Church:,5)

    !nsert intotbl$mployee values(:Todd:,:0ale:,:-ydney: ,=)

    !nsert intotbl$mployee values(:4en:,:0ale:,:New 1elhi:,5)

    !nsert intotbl$mployee values(:-ara:,:emale:,:'ondon:,=)

    his is what we want to achieve

    ".1isplay all the departments from tbl+epartmentstable. The 1epartment names should

    be rendered as hyperlins.#.n clicing the department name link, all the employees in the department should be

    displayed. The employee names should be rendered as hyperlins.

    (.n clicing the employee name link, the full details of the employee should be

    displayed.

    /.A lin should also be provided on the employee full details page to navigate bac

    tomployee list page. Along the same lines, a lin should also be provided on the

    employee list page to navigate bac to 1epartments list page.

    he screen shots of the above workflow is shown below for your reference

  • 7/23/2019 Hands on Lab Mvc

    4/15

    Implementing +epartments 0ist*

    1tep "*ight clic on the 'Models'folder and add a class file with name%+epartment.cs.

    Copy and paste the following code.

    using-ystem&

    using-ystem.Collections.>eneric&

    using-ystem.'inD&

    using-ystem.Web&using-ystem.Component0odel.1ataAnnotations.-chema&

    namespace0*C1emo.0odels

    #

    ETable(tbl1epartment)F

    public class1epartment

    #

    public int!1 # get& set&+

    public stringName # get& set&+

    public'ist$mployee $mployees # get& set&+

    ++

    1tep #*Add '+epartments'property to 'mployeeContext'class that is present

    in'mployeeContext.cs'file in 'Models'folder.

    public class$mployeeConte"t 3 1bConte"t

    #

    public1b-et1epartment 1epartments # get& set&+

    public1b-et$mployee $mployees # get& set&+

    +

    1tep (*ight clic on the 'Controllers'folder and add a Controller, withname%+epartmentController. Copy and paste the following code.

    using-ystem&

    using-ystem.Collections.>eneric&

    using-ystem.'inD&

    using-ystem.Web&

    using-ystem.Web.0vc&

    using0*C1emo.0odels&

  • 7/23/2019 Hands on Lab Mvc

    5/15

    namespace0*C1emo.Controllers

    #

    public class1epartmentController 3 Controller

    #

    publicActionesult !nde"() #

    $mployeeConte"t employeeConte"t % new $mployeeConte"t()&

    'ist1epartment departments % employeeConte"t.1epartments.To'ist()&

    return *iew(departments)&

    +

    +

    +

    1tep /*ight clic on the Index() action method in +epartmentControllerclass and

    select '2dd View'from the conte"t menu. -et

    *iew name % Index*iew engine % $a%or

    -elect 'Create 1trongly&typed view' checbo"

    -elect +epartmentclass, from 'Model class'dropdownlist

    Clic '2dd'button

    Copy and paste the following code in Index.cshtml view file in +epartment folder

    /using 0*C1emo.0odels&

    /model !$numerable1epartment

    div style%font2family3Arial/#

    *iew4ag.Title % 1epartments 'ist&

    +

    h51epartments 'ist6h5

    ul

    /foreach (1epartment department in /0odel)

    #

    li/7tml.Action'in(department.Name, !nde", $mployee,

    new # department!d % department.!1 +, null)6li

    +6ul

    6div

    Changes to mployee 0ist and +etail pages

    Add '+epartmentId'property to 'mployee'model class that is present

    inmployee.csfile in 'Models'folder.

    ETable(tbl$mployee)F

  • 7/23/2019 Hands on Lab Mvc

    6/15

    public class$mployee

    #

    public int$mployee!d # get& set&+

    public stringName # get& set&+

    public string>ender # get& set&+

    public stringCity # get& set&+ public int1epartment!d # get& set&+

    +

    Add 'departmentId'parameter to Index() action method in 'mployeeController'class

    that is present in 'mployeeController.cs'file in 'Controllers'folder. Gse

    the'departmentId'parameter to filter the list of employees as shown below.

    publicActionesult !nde"(int department!d)

    #

    $mployeeConte"t employeeConte"t % new $mployeeConte"t()&

    'ist$mployee employees % employeeConte"t.$mployees.Where(emp %

    emp.1epartment!d %% department!d).To'ist()&

    return *iew(employees)&

    +

    Copy and paste the following line in 'Index.cshtml'that is present in 'mployee'folder

    in 'Views'folder. With this change we are able to generate an action lin to redirect the

    user to a different controller action method.

    /7tml.Action'in(4ac to 1epartment 'ist, !nde", 1epartment)

    Change the following line in '+etails.cshtml'that is present in 'mployee'folder

    in'Views'folder.C7AN>$ T7!- '!N$ /7tml.Action'in(4ac to 'ist, !nde")

    T

    /7tml.Action'in(4ac to $mployee 'ist, !nde", new # department!d

    %/0odel.1epartment!d +)

    we will discuss using business ob3ects as model.

  • 7/23/2019 Hands on Lab Mvc

    7/15

    Gntil now, we have been using entity framewor and entities. $ntities are mapped to

    database tables, and obHect relational mapping tools lie $ntity ramewor, n7ibernate, etc

    are used to retrieve and save data. 4usiness obHects contain both state(data) and

    behaviour, that is logic specific to the business.

    In MVC there are several conventions that needs to be followed.or e"ample,

    controllers need to have the word controller in them and should implement !Controller

    interface either directly or indirectly. *iews should be placed in a specific location that 0*C

    can find them.

    public class7omeController 3 Controller

    #

    public *iewesult !nde"()

    #

    *iew1ataECountriesF % new 'iststring()

    #

    !ndia,

    G-,

    G

  • 7/23/2019 Hands on Lab Mvc

    8/15

    8ut with models, there are no strict rules.!nfact 'Models'folder is optional and they can

    live anywhere. They can even be present in a separate proHect.

    'et:s now turn our attention to using business obHects as model. We will be using

    table'tblmployee'for this demo. Gse the sDl script to create and populate this table.

    Create tabletbl$mployee

    (

    !d int ;rimary ender nvarchar(=9),

    City nvarchar(89),

    1atef4irth 1ateTime

    )

    !nsert intotbl$mployee values(:0ar:,:0ale:,:'ondon:,:9=6986=JKJ:)

    !nsert intotbl$mployee values(:?ohn:,:0ale:,:Chennai:,:9@69K6=JL=:)!nsert intotbl$mployee values(:0ary:,:emale:,:New Bor:,:9569M6=JKL:)

    !nsert intotbl$mployee values(:0ie:,:0ale:,:-ydeny:,:9569@6=JKM:)

    !nsert intotbl$mployee values(:-cott:,:0ale:,:'ondon:,:9M696=JK5:)

    1tored procedure to retrieve data

    Create proceduresp>etAll$mployees

    as

    4egin

    -elect!d, Name, >ender, City, 1atef4irth

    from tbl$mployee

    $nd

    1tep "*Create an A-;.N$T 0*C M Web application with name % MVC+emo

    1tep #*Add a Class 'ibrary proHect with Name%'8usiness0ayer'

    1tep (*ight clic on the 8usiness0ayer class library proHect, and add a class file with

    name % mployee.cs.

    using-ystem&

    using-ystem.Collections.>eneric&

    using-ystem.'inD&

    using-ystem.Te"t&

    namespace4usiness'ayer

    #

    public class$mployee

    #

    public int!1 # get& set&+

    public stringName # get& set&+

  • 7/23/2019 Hands on Lab Mvc

    9/15

    public string>ender # get& set&+

    public stringCity # get& set&+

    public1ateTime 1atef4irth # get& set&+

    +

    +

    1tep /*ight clic on the '$eferences'folder of the '8usiness0ayer'class library

    proHect, and add a reference to '1ystem.Configuration'assembly.

    1tep 9*ight clic on the 8usiness0ayerclass library proHect, and add a class file with

    name % mployee8usiness0ayer.cs.

    using-ystem&

    using-ystem.Collections.>eneric&

    using-ystem.'inD&

    using-ystem.Te"t&

    using-ystem.1ata&

    using-ystem.1ata.-DlClient&using-ystem.Configuration&

    namespace4usiness'ayer

    #

    public class$mployee4usiness'ayer

    #

    public !$numerable$mployee $mployees

    #

    get

    #

    string connection-tring % Configuration0anager.Connection-tringsE14C-F.Connection-tring&

    'ist$mployee employees % new 'ist$mployee()&

    using (-DlConnection con % new-DlConnection(connection-tring))

    #

    -DlCommand cmd % new -DlCommand(sp>etAll$mployees, con)&

    cmd.CommandType % CommandType.-tored;rocedure&

    con.pen()&

    -Dl1ataeader rdr % cmd.$"ecuteeader()&

    while (rdr.ead()) #

    $mployee employee % new $mployee()&

    employee.!1 % Convert.To!nt@5(rdrE!dF)&

    employee.Name % rdrENameF.To-tring()&

    employee.>ender % rdrE>enderF.To-tring()&

    employee.City % rdrECityF.To-tring()&

    employee.1atef4irth % Convert.To1ateTime(rdrE1atef4irthF)&

  • 7/23/2019 Hands on Lab Mvc

    10/15

    employees.Add(employee)&

    +

    +

    return employees& +

    +

    +

    +

    1tep :*ight clic on the '$eferences'folder of the 'MVC+emo'proHect, and add a

    reference to '8usiness0ayer'proHect.

    1tep ;*!nclude a connection string with name < '+8C1'in Web.Config file

    add name%14C-

    connection-tring%server%.& database%-ample& integrated security%--;! providerName%-ystem.1ata.-DlClient6

    1tep =*ight clic on the 'Controllers'folder and add Controller with name

    %'mployeeController.cs'.

    public class$mployeeController 3 Controller

    #

    publicActionesult !nde"()

    #

    $mployee4usiness'ayer employee4usiness'ayer %

    new $mployee4usiness'ayer()&

    'ist$mployee employees % employee4usiness'ayer.$mployees.To'ist()&

    return *iew(employees)&

    +

    +

    1tep >*ight clic on the Index() action method in the 'mployeeController'class and

    select '2dd View'from the conte"t menu. -et

    *iew name % Index

    *iew engine % $a%or

    -elect 'Create a strongly&typed view'checbo"

    -caffold Template % 0istClic '2dd'button

    un the application and navigate to http366localhost60*C1emo6$mployee6!nde". The output

  • 7/23/2019 Hands on Lab Mvc

    11/15

    should be as shown below.

    we will discuss, creating a view to insert a new employee into

    the database

    table tblmployee.

    We want to present the end user with a form as shown in the image below

  • 7/23/2019 Hands on Lab Mvc

    12/15

    Copy and paste the following 'Create'action method, in mployeeControllerclass.

    E7ttp>etF

    publicActionesult Create()

    #

    return *iew()&

    +

    ;lease note that, the method is decorated with '6ttp?et'attribute. This maes this action

    method to respond only to the '?'reDuest.

    Now let:s add a 'Create'view. To do this, right clic on the 'Create'action method and

    select '2dd View'from the conte"t menu. -et

    ".*iew name % 'Create'

    #.*iew engine % '$a%or'

    (.-elect 'Create 1trongly&typed view'checbo"

    /.-elect 'mployee'class, from 'Model class'dropdownlist

    9.-caffold Template % Create:.Clic '2dd'button

    At this point 'Create.cshtml'view will be added in 'mployee'folder. !f you have the

    following '1cripts'section at the bottom of the view, please delete it. We will discuss about

    sections and scripts in later lab.

    /section -cripts #

    /-cripts.ender(I6bundles6HDueryval)

    +

    $un the application and navigate to the following $0

    http366localhost60*C1emo6$mployee6!nde"

    Click on 'Create @ew' link. Aou will be naviaged to the following $0

    http366localhost60*C1emo6$mployee6Create

    A form with te"tbo"es to add a new employee is rendered. or employee '?ender'it is

    ideal to have a dropdownlist instead of a te"t bo". To achieve this, $;'AC$ T7$

    ''W!N> '!N$

    /7tml.$ditoror(model % model.>ender)

    W!T7

    /7tml.1rop1own'ist(>ender, new 'ist-elect'ist!tem#

    new -elect'ist!tem # Te"t % 0ale, *alue%0ale+,

    new -elect'ist!tem # Te"t % emale, *alue%emale+

    +, -elect >ender)

    un the application and notice that, a dropdownlist is now displayed for '?ender'.

  • 7/23/2019 Hands on Lab Mvc

    13/15

    !f you clic on 'Create'button, you will get an error message stating 2 The resource cannot

    be found. This is because we don:t have the 'Create'controller action method that can

    handle 6))ostreDuest.

    we will discuss using BormCollection ob3ect in mvc and it!s

    purpose

    BormCollection class will automatically receive the posted form values in the controller

    action method, in key7valuepairs. eysO valuescan be accessed using ey names or

    inde".

    We implemented the following 'Create' view in

    We can use the BormCollection to loop thru each ey and it:s value that is posted to the

    server.

    E7ttp;ostF

    publicActionesult Create(ormCollection formCollection)

    #

    if (0odel-tate.!s*alid)

    #

    foreach (string ey in formCollection.All

  • 7/23/2019 Hands on Lab Mvc

    14/15

    esponse.Write(ender nvarchar(=9),

    /City nvarchar(89),

    /1atef4irth 1ateTime

    as

    4egin

    !nsert intotbl$mployee (Name, >ender, City, 1atef4irth)

    *alues (/Name, />ender, /City, /1atef4irth)

    $nd

    2dd the following method to mployee8usiness0ayer.cs file.

    public voidAdd$mmployee($mployeeemployee)

    #

    string connection-tring %

    Configuration0anager.Connection-tringsE14C-F.Connection-tring&

    using (-DlConnection con % new -DlConnection(connection-tring))

    #

    -DlCommand cmd % new -DlCommand(spAdd$mployee, con)&

    cmd.CommandType % CommandType.-tored;rocedure&

    -Dl;arameterparamName % new-Dl;arameter()&

    paramName.;arameterName % /Name&

    paramName.*alue % employee.Name&

    cmd.;arameters.Add(paramName)&

    -Dl;arameterparam>ender % new-Dl;arameter()&

    param>ender.;arameterName % />ender&

  • 7/23/2019 Hands on Lab Mvc

    15/15

    param>ender.*alue % employee.>ender&

    cmd.;arameters.Add(param>ender)&

    -Dl;arameterparamCity % new-Dl;arameter()&

    paramCity.;arameterName % /City&

    paramCity.*alue % employee.City& cmd.;arameters.Add(paramCity)&

    -Dl;arameterparam1atef4irth % new-Dl;arameter()&

    param1atef4irth.;arameterName % /1atef4irth&

    param1atef4irth.*alue % employee.1atef4irth&

    cmd.;arameters.Add(param1atef4irth)&

    con.pen()&

    cmd.$"ecuteNonQuery()&

    +

    +

    o save form data, to a database table, copy and paste the following code

    inmployeeController.csfile.

    E7ttp;ostF

    publicActionesult Create(ormCollection formCollection)

    #

    $mployee employee % new$mployee()&

    66 etrieve form data using form collection

    employee.Name % formCollectionENameF&

    employee.>ender % formCollectionE>enderF&

    employee.City % formCollectionECityF& employee.1atef4irth %

    Convert.To1ateTime(formCollectionE 1atef4irthF)&

    $mployee4usiness'ayer employee4usiness'ayer %

    new $mployee4usiness'ayer()&

    employee4usiness'ayer.Add$mmployee(employee)&

    return edirectToAction(!nde")&

    +

    1o we really have to write all the dirty code of retrieving data from BormCollection andassign it to the properties of 'employee'obHect. The answer is no. This is the Hob of

    themodelbinderin 0*C.