26
Models in MVC Eyal Vardi CEO E4D Solutions LTD Microsoft MVP Visual C# blog: www.eVardi.com

Models

Embed Size (px)

DESCRIPTION

ASP.NET MVC .30 - Models

Citation preview

Page 1: Models

Models in MVC

Eyal VardiCEO E4D Solutions LTDMicrosoft MVP Visual C#blog: www.eVardi.com

Page 2: Models

Models in MVC

Eyal VardiCEO E4D Solutions LTDMicrosoft MVP Visual C#blog: www.eVardi.com

Page 3: Models

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

Agenda

Integrating the Model & Controller

Model Binders

Model Validation

Page 4: Models

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

Model Template

What Is a Model?

Model

Controller

View HTTPHTML

Deserialization

Template

Page 5: Models

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

Model Attributes

Scaffolding [ScaffoldColumn]

View [HiddenInput] [Display] [DisplayName], Attribute on a Class [DataType(...)] [UIHint(...)] [AdditionalMetadata( key , value )]

Page 6: Models

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

Display Attribute[DisplayName("Book")]     public class E4DBook     {         

[Display(Name = "Title")]         

public string E4DTitle { get; set; }     }

Model

<h2>@Html.LabelForModel()</h2>

@Html.EditorForModel()

Or

@Html.LabelFor(m => m.E4DTitle)

View

Page 7: Models

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

DataType Attribute

DateTime

Date

Time

Text

MultilineText

Password

Url

EmailAddress

Page 8: Models

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

UIHint Attribute

Use the UIHint attribute to specify the template we want to use to render HTML for a property.

[DisplayName("Book")]     public class E4DBook     {         

[Display(Name = "Title")][DateType(DataType.MultilineText)][UIHint("MultilineText")]         

public string E4DTitle { get; set; }     }

Model

Page 9: Models

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

Built in View Template

Boolean Collection Decimal EmailAddress HiddenInput Html MultilineText

Object Password String Text Url

Page 10: Models

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

Model Templates

Page 11: Models

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

Model Binding

What Is a Model?

Model

Controller

View HTTPHTML

Deserialization

Template

Page 12: Models

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

HTTP to .NET Classes

public ActionResult Index(Reservation reservation){    // TODO BL.    return View( reservation );} Deserialization

Page 13: Models

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

Model Binders

Binders are like type converters, because they can convert HTTP requests into objects that are passed to an action method.

Page 14: Models

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

DefaultModelBinder Class

Translate HTTP request into complex models, including nested types and arrays. URL Form data, Culture - Sensitive

1. Request.Form

2. RoutedData.Values

3. Request.QueryString

4. Request.Files

(Key,Value)

Page 15: Models

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

Binding to Complex Types[DisplayName("Book")]     public class E4DBook     {         

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

public Reservation MyReservation { get; set; }    }

Model

<label for="MyReservation_FlightNum">FlightNum</label>         

<input type="text" value=""                  id = "MyReservation_FlightNum"                   name = "MyReservation.FlightNum"  />

Html

 @Html.LabelFor(model => model.MyReservation.FlightNum)          @Html.EditorFor(model => model.MyReservation.FlightNum) 

View

Page 16: Models

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

Specifying Custom Prefixes

<!– First Arg --><label for="FlightNum">FlightNum</label><input type="text" id="FlightNum" name="FlightNum"  />

...

<!– Second Arg --><label for="MyRes_FlightNum">FlightNum</label><input type="text" id="MyRes_FlightNum" name="MyRes.FlightNum"  />

Html

public ActionResult Index( Reservation res1 , [Bind(Prefix="myRes")] Reservation res2 ) { ... }

Controller

Page 17: Models

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

Bind Attribute (“View”)

Represents an attribute that is used to provide details about how model binding to a parameter should occur.

[Bind(Include = "FlightNum, TravelDate)]public class Reservation{    public int FlightNum { get; set; }    public DateTime TravelDate { get; set; }    public int TicketCount { get; set; }    public int DiscountPercent { get; set; }}

Page 18: Models

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

Bind Attribute

Page 19: Models

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

<input type="text" name="reservation" value="…" /><input type="text" name="reservation" value="…" /><input type="text" name="reservation" value="…" /><input type="text" name="reservation" value="…" />

Html

public ActionResult Index( List< string > reservation ) { ... }

Controller

Binding to a String Collections

Page 20: Models

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

Binding to a Collections

<!– Option I--><input type="text" name="[0].Name"  /><input type="text" name="[1].Name"   />

<!– Option II --><input type="hidden" name="Index" value="f1"   /><input type="text" name="[f1].Name"  />

<input type="hidden" name="Index" value="f2"   /><input type="text" name="[f2].Name"  />

Html

public ActionResult Index( List<Reservation> reservation ) { ... }

Controller

Page 21: Models

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

Binding to a Dictionary

<input type="hidden" name="[0].key" value="f1"   /><input type="text" name="[0].value.Name"  />

<input type="hidden" name="[1].key" value="f2"   /><input type="text" name="[1].value.Name"  />

Html

public ActionResult Index( Dictionary<Reservation> reservation ) { ... }

Controller

Page 22: Models

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

Manually Invoking Model Binding

Page 23: Models

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

Custom Model Binders

ASP.NET MVC allows us to override both the default model binder, as well as add custom model binders.

ModelBinders.Binders.DefaultBinder = new CustomDefaultBinder();

ModelBinders.Binders.Add( typeof(DateTime), 

new DateTimeModelBinder() );

Page 24: Models

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

ModelBinder Attribute

Represents an attribute that is used to associate a model type to a model-builder type.

public ActionResult Contact( [ModelBinder(typeof(ContactBinder))] Contact contact ){      ViewData["name"]  = contact.Name;      ViewData["email"]  = contact.Email;      ViewData["message"] = contact.Message;      ViewData["title"]  = "Succes!";

      return View();}

Page 25: Models

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

Custom Binder

Page 26: Models

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

Integrating The Model & Controller

public ActionResult Index(Reservation reservation){    int totalCost = reservation.TicketCount * 100;

   if (reservation.DiscountPercent != 0)    {        totalCost -= (totalCost * reservation.DiscountPercent / 100);    }

    ViewBag.TotalCost = totalCost;

    return View( reservation );}

Deserialization

BL

@model Reservation

Model

Index.cshtml