Skip to content

SELECT DISTINCT and ORDER BY

March 27, 2013

 

Came across an interesting issue today. The following link shed some light on my confusion.

http://weblogs.sqlteam.com/jeffs/archive/2007/12/13/select-distinct-order-by-error.aspx

How to get the generated query from IQueryable<T> from entity framework

March 19, 2013

You can get the query to be generated by entity framework by type casting the IQueryable to ObjectQuery and call it’s ToTraceString() method…

((ObjectQuery<TypeOfData>) results).ToTraceString();

Member Scope in JavaScript

March 19, 2013

Most of this is going to be straight out of code, with some comments to explain it a little bit.

Should be pretty straight forward.

var obj = function() {

            //#region private variables

            var _privateName = ‘Private Object’;

            //#endregion

           

            //#region public properties

            this.publicName = ‘Public Object’;

            //#endregion

           

            //#region private methods

            var privateName = function () {

                console.log(‘My private name is ‘ + _privateName);

            };

            //#endregion

           

            //#region public methods

            this.myInstanceName = function () {

                console.log(‘My instance name from the object definition is ‘ + this.publicName + ‘ / ‘ + _privateName );

            };

            this.callPrivateMethod = function() {

                privateName();

            };

            //#endregion

        };

 

        //#region static properties/methods

        obj._staticName = "Static Name";

        obj.staticName = function() {

            console.log(‘My static name is ‘ + obj._staticName);

        };

        //#endregion

 

        //#region instance methods

        obj.prototype.instanceName = function() {

            console.log(‘My instance name is ‘ + this.publicName);

            //you can not access private variables from instance methods (methods on the prototype)

            //error : Uncaught ReferenceError: _privateName is not defined

            //console.log(‘My instance name is ‘ + this.publicName + ‘ / ‘ + _privateName);

        };

        //#endregion

 

        obj.staticName();

        var t = new obj();

        t.myInstanceName();

        t.instanceName();

        //try to access the privateName from the object instance

        //t.privateName();

        //error on the above line "Uncaught TypeError: Object [object Object] has no method ‘privateName’ "

 

        //try to call the privateName from a public method

        t.callPrivateMethod();

 

        //try to call the static methods from an instance

        //error: Uncaught TypeError: Object [object Object] has no method ‘staticName’

        //t.staticName();

       

        //try to call a instance public instance method using the class name

        /*

         error: Uncaught TypeError: Object function () {

            //#region private variables

            var _privateName = ‘Private Object’;

            //#endregion

           

            //#region public properties

            this.publicName = ‘Public Object’;

            //#endregion

           

            //#region private methods

            var privateName = function () {

                console.log(‘My private name is ‘ + _privateName);

            };

            //#endregion

           

            //#region public methods

            this.myInstanceName = function () {

                console.log(‘My instance name from the object definition is ‘ + this.publicName + ‘ / ‘ + _privateName );

            };

            this.callPrivateMethod = function() {

                privateName();

            };

            //#endregion

        } has no method ‘myInstanceName’

        */

        //obj.myInstanceName();

       

 

        //out put of the valid calls is

       

        //My static name is Static Name localhost:38

        //My instance name from the object definition is Public Object / Private Object localhost:27

        //My instance name is Public Object localhost:44

        //My private name is Private Object

 

        obj.dualFace = function() {

            if (this instanceof obj) {

                console.log(‘dual face instance’);

            }

            else {

                console.log(‘dual face static’);

            }

        };

 

        obj.prototype.dualFace = function() {

            obj.dualFace.call(this);

        };

 

        obj.dualFace();

        t.dualFace();

       

        //dual face static localhost:108

        //dual face instance

 

For private static members, we need to do a little trick.

you need a function to act as a closure and wrap around the private members. Then let’s have the same wrapper function execute immediately and return a new function. The returned function value is assigned to the variable Gadget and becomes the new constructor:

var Gadget = (function () { 
            // static variable/ property 
            var counter = 0; 
            // returning the new implementation 
            // of the constructor 
            return function() {
                 console.log( counter + = 1);
            }; 
        }()); // execute immediately

Declaring Objects in JavaScript

March 18, 2013

When you think about objects in JavaScript, simply think about hash tables of key-value pairs (similar to what are called “associative arrays” in other languages). The values can be primitives or other objects; in both cases they are called properties. The values can also be functions, in which case they are called methods.

var dog = {

    name: "Benji",

    getName: function () { return this.name; }

};

If you’re not used to the object literal notation, it may look a little odd at the beginning, but the more you use it, the more you’ll love it. In essence, the syntax rules are:

·         Wrap the object in curly braces ({ and }).

·         Comma-delimit the properties and methods inside the object. A trailing comma after the last name-value pair is allowed but produces errors in IE, so don’t use it.

·         Separate property names and property values with a colon.

·         When you assign the object to a variable, don’t forget the semicolon after the closing }.

 

There are no classes in JavaScript and this allows for great flexibility, because you don’t have to know anything about your object in advance; you don’t need a class “blueprint.” But JavaScript also has constructor functions, which use syntax similar to the class-based object creation in Java or other languages.
You can create objects using your own constructor functions or using some of the built-in constructors such as Object(), Date(), String() and so on. Here’s an example showing two equivalent ways to create two identical objects:

// one way — using a literal

var car = { goes: "far" };

// another way — using a built-in constructor

// warning: this is an antipattern

var car = new Object();

car.goes = "far";

In addition to the object literal pattern and the built-in constructor functions, you can create objects using your own custom constructor functions, as the following example demonstrates:

var adam = new Person(" Adam");

adam.say(); // "I am Adam"

This new pattern looks very much like creating an object in Java using a class called Person. The syntax is similar, but actually in JavaScript there are no classes and Person is just a function.

Here’s how the Person constructor function could be defined.

var Person = function(name) {

    this.name = name;

    this.say = function() {

         return "I am " + this.name;

    };

};

When you invoke the constructor function with new, the following happens inside the function:

·         An empty object is created and referenced by this variable, inheriting the prototype of the function.

·         Properties and methods are added to the object referenced by this.

·         The newly created object referenced by this is returned at the end implicitly (if no other object was returned explicitly).

It’s as if something like this happens behind the scenes:

var Person = function (name)

{   // create a new object

    // using the object literal

    // var this = {};

    // add properties and methods

    this.name = name;

    this.say = function() {

         return "I am " + this.name;

    };

    // return this;

};

 

For simplicity in this example, the say() method was added to this. The result is that any time you call new Person() a new function is created in memory. This is obviously inefficient, because the say() method doesn’t change from one instance to the next. The better option is to add the method to the prototype of Person:

Person.prototype.say = function() {

     return "I am " + this.name;

};

When invoked with new, a constructor function always returns an object; by default it’s the object referred to by this. If you don’t add any properties to this inside of your constructor, an “empty” object is returned (“ empty” aside from inheriting from the constructor’s prototype).

Constructors implicitly return this, even when you don’t have a return statement in the function.

As mentioned already, constructors are still just functions but invoked with new. What happens if you forget new when you invoke a constructor? This is not going to cause syntax or runtime errors but might lead to logical errors and unexpected behavior. That’s because when you forget new, this inside the constructor will point to the global object. (In browsers this will point to window.)

When your constructor has something like this.member and you invoke the constructor without new, you’re actually creating a new property of the global object called member and accessible through window.member or simply member. This behavior is highly undesirable, because you know you should always strive for keeping the global namespace clean.

function Waffle() {

     if (!(this instanceof Waffle)) {

          return new Waffle();

     }

    this.tastes = "yummy";

}

Waffle.prototype.wantAnother = true;

// testing invocations

var first = new Waffle(),

    second = Waffle();

console.log(first.tastes);// "yummy"

console.log(second.tastes); // "yummy"

console.log(first.wantAnother); // true

console.log(second.wantAnother); // true

Stefanov, Stoyan (2010-09-09). JavaScript Patterns (Kindle Locations). O’Reilly Media. Kindle Edition.

Globals in Javascript

March 18, 2013

It is surprisingly easy to create globals involuntarily because of two JavaScript features. First, you can use variables without even declaring them. And second, JavaScript has the notion of implied globals, meaning that any variable you don’t declare becomes a property of the global object (and is accessible just like a properly declared global variable). Consider the following example:

function sum( x, y)

{ // antipattern: implied global

    result = x + y; return result;

}

In this code, result is used without being declared. The code works fine, but after calling the function you end up with one more variable result in the global namespace that can be a source of problems. The rule of thumb is to always declare variables with var, as demonstrated in the improved version of the

function sum(x, y) {

     var result = x + y; return result;

}

 

Another antipattern that creates implied globals is to chain assignments as part of a var declaration. In the following snippet, a is local but b becomes global, which is probably not what you meant to do:

// antipattern, do not use

function foo() {

    var a = b = 0;

    // …

}

If you’re wondering why that happens, it’s because of the right-to-left evaluation. First, the expression b = 0 is evaluated and in this case b is not declared. The return value of this expression is 0, and it’s assigned to the new local variable declared with var a. In other words, it’s as if you’ve typed:

var a = (b = 0);

If you’ve already declared the variables, chaining assignments is fine and doesn’t create unexpected globals. Example:

function foo()

{

    var a, b;

    // …

    a = b = 0; // both local

}

 

There’s one slight difference between implied globals and explicitly defined ones — the difference is in the ability to undefine these variables using the delete operator: Globals created with var (those created in the program outside of any function) cannot be deleted. Implied globals created without var (regardless if created inside functions) can be deleted. This shows that implied globals are technically

 

Stefanov, Stoyan (2010-09-09). JavaScript Patterns (Kindle Locations). O’Reilly Media. Kindle Edition.

Using KnockOut JS for MVVM pattern on the client side PART 1

March 18, 2013

 

We have three main parts to the MVVM patter, the View, the Model, and the ViewModel. The view model holds the model (which is generally just the representation of data as it would be in your storage layer) and any other information as in lists, event handlers etc that the view would need. I’m using knock out to the implement the MVVM pattern on the client side. I’ve setup a simple demo. The two files of interest are the MVC partial view and the .js file that has my view models.

The partial view in MVC looks like

@*I’m not too concerned about the formatting for the purpose of this demo*@

@*Setting up the view to display the information (readonly)*@

<fieldset>

    <legend>Dispaly Information</legend>

 

    <div id="displayInfo" data-bind="with: model">

        <p>Account Id : <strong data-bind="text: AccountId"></strong></p>

        <p>Name : <strong data-bind="text: Name"></strong></p>

        <p>Description: <strong data-bind="text: Description"></strong></p>

        <p>Description: <strong data-bind="text: OpenDate"></strong></p>

        <p>Active: <strong data-bind="text: Active"></strong></p>

        <p>

            Active:

        <select data-bind="options: $root.activeOptions, value:Active"></select>

        </p>

    </div>

</fieldset>

@*set up the search form*@

<fieldset>

    <legend>Search Form</legend>

 

    <div id="searchFields" data-bind="with: model">

        <p>

            Name :

            <input type="text" data-bind="value: Name" />

        </p>

        <p>

            Description :

            <input type="text" data-bind="value: Description" />

        </p>

        <p>

            Active :

            <select data-bind="options: $root.activeOptions, value:Active"></select>

        </p>

        <p>

            <input type="button" value="Search Records" data-bind="click: $root.searchButtonClicked" />

        </p>

    </div>

</fieldset>

@*import the javascript file that holds the view models for this view*@

<script src="~/Scripts/baseFrameworkAccounts.js"></script>

<script>

    //initiate the two view models to bind to the view

    accountsKO.editViewModel.init();

    accountsKO.searchViewModel.init();

</script>

The Javascript file looks like

//setup my module in js

if (!window.accountsKO) {

    window.accountsKO = (function () {

        //since this is going to be shared between two

        //view models, i’m going to leave it global in this scope

        var activeOptions = ["No selected", "Yes", "No"];

 

        //region edit view model

 

        var editViewModel = function () {

            var self = this;

            //define the model

            //we are assuming the values from this model is coming from some persistant

            //store. later I will modify this to get these values from the db

            self.model = {

                AccountId: ko.observable(‘GUID’),

                Name: ko.observable(‘Saaed’),

                Description: ko.observable(‘Knock Out Test’),

                OpenDate: ko.observable(new Date()),

                Active: ko.observable(‘Yes’)

            };

            //i’m going to use the init method to initialize my view model

            self.init = function () {

                //apply the view model binding to the view

                ko.applyBindings(this, document.getElementById("displayInfo"));

            }

            self.activeOptions = activeOptions;

        }

       

        //end region edit view model

 

        //region searhc screen

 

        var searchViewModel = function () {

            var self = this;

            //define the model

            self.model = {

                Name: ko.observable(‘bound’),

                Description: ko.observable(”),

                Active: ko.observable(”)

            };

            self.init = function () {

                //apply the view model binding to the view

                ko.applyBindings(this, document.getElementById("searchFields"));

            }

            self.activeOptions = activeOptions;

            self.searchButtonClicked = function () {

                //you can do something more meaningful here

                //i’m just going to output the selection to the console log

                console.log(‘search name : ‘ + self.model.Name());

                console.log(‘search description : ‘ + self.model.Description());

                console.log(‘search active : ‘ + self.model.Active());

             }

        };

        //end region search screen

       

        //when this module is iniated

        //return this object with the two view models

        var rtv = {

            editViewModel: new editViewModel(),

            searchViewModel: new searchViewModel()

        }

 

        return rtv;

    }());

}

I will keep modifying this little demo to get the whole life cycle going. which is, from db layer to dto from the dto to the service layer, from the service layer to the controller in MVC and from there to the client layer (views and javascript). And back.

capture

Getting TOP 1 in Oracle when records are ordered Desc

March 15, 2013

 

To order a record by Date in descending order and get the first record in SQL Server we us the top 1 clause

SELECT TOP 1 ERROR_MESSAGE FROM ERRORS WHERE RECORD_ID = @RecordId ORDER BY TIME_STAMP DESC

To do the same thing in Oracle, I used the ROWNUM function as

SELECT ERROR_MESSAGE FROM ERRORS WHERE RECORD_ID = @RecordId AND ROWNUM = 1 ORDER BY TIME_STAMP DESC

But this gave me the wrong results, because in oracle the ROWNUM is applied before the the result is ordered. So the end result is incorrect. To do this correctly and to get the desired result, we need to order the records in a subquery and then apply the ROWNUM in the outer select.

SELECT ERROR_MESSAGE  FROM

(SELECT ERROR_MESSAGE FROM ERRORS WHERE RECORD_ID = @RecordId ORDER BY TIME_STAMP DESC)

WHERE ROWNUM = 1

 

And now I know.

Basics of rendering edit forms in mvc

March 14, 2013

There is not much explanation today, I’m running short on time and I need to put this online before I for get.

The Model class is

[DisplayName("User Registration")]

    public class Registration

    {

       

        //[HiddenInput]

        [HiddenInput(DisplayValue=false)]

        public string AccountId { get; set; }

       

        [Display(Name = "Name")]

        [Required(ErrorMessage="Name is required")]

        public string Name { get; set; }

 

        [Display(Name = "Description")]

        [Required(ErrorMessage = "Description is required")]

        public string Description { get; set; }

 

        [Display(Name = "Open Date")]

        [Required(ErrorMessage="Open Date is required")]

        public DateTime OpenDate { get; set; }

 

        [Display(Name = "Active")]

        public bool? Active { get; set; }

    }

 

The controller is

public class AccountsController : Controller

    {

        //

        // GET: /Accounts/

 

        public ActionResult Register()

        {

            Registration register = new Registration();

            return View(register);

        }

 

    }

 

The View is

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

 

<fieldset>

    <legend>EditorForModel</legend>

 

    @using (Html.BeginForm())

    {

 

        @Html.EditorForModel()

 

    }

</fieldset>

 

<fieldset>

    <legend>Formated EditorForModel</legend>

 

    @using (Html.BeginForm())

    {

        <div class="formatededitorformodel">

            @Html.EditorForModel()

        </div>

 

    }

</fieldset>

 

 

<fieldset>

    <legend>DisplayNameFor/TextBoxFor</legend>

 

    @using (Html.BeginForm())

    {

        <div class="formview">

            @Html.HiddenFor(c => c.AccountId)

 

            <label>@Html.DisplayNameFor(c => c.Name)</label>

            <span>@Html.TextBoxFor(c => c.Name)</span>

            <br />

            <label>@Html.DisplayNameFor(c => c.Description)</label>

            <span>@Html.TextBoxFor(c => c.Description)</span>

            <br />

            <label>@Html.DisplayNameFor(c => c.OpenDate)</label>

            <span>@Html.TextBoxFor(c => c.OpenDate)</span>

            <br />

            <label>@Html.DisplayNameFor(c => c.Active)</label>

            <span>@Html.DropDownListFor(c => c.Active, new[]{

             new SelectListItem(){Text="Yes",Value=Boolean.TrueString},

             new SelectListItem(){Text="No",Value=Boolean.FalseString}

         }, "Not Set")

            </span>

 

            @*using a editor template to render a checkbox for my nullable bool*@

            <label>Custom Bool</label>

            <span>@Html.EditorFor(c => c.Active, "CustomBoolean")</span>

 

        </div>

    }

</fieldset>

 

<fieldset>

    <legend>DisplayNameFor/EditorFor</legend>

 

    @using (Html.BeginForm())

    {

        <div class="formview">

            @Html.HiddenFor(c => c.AccountId)

 

            <label>@Html.DisplayNameFor(c => c.Name)</label>

            <span>@Html.EditorFor(c => c.Name)</span>

            <br />

            <label>@Html.DisplayNameFor(c => c.Description)</label>

            <span>@Html.EditorFor(c => c.Description)</span>

            <br />

            <label>@Html.DisplayNameFor(c => c.OpenDate)</label>

            <span>@Html.EditorFor(c => c.OpenDate)</span>

            <br />

            <label>@Html.DisplayNameFor(c => c.Active)</label>

            <span>@Html.DropDownListFor(c => c.Active, new[]{

             new SelectListItem(){Text="Yes",Value=Boolean.TrueString},

             new SelectListItem(){Text="No",Value=Boolean.FalseString}

         }, "Not Set")

            </span>

 

            @*using a editor template to render a checkbox for my nullable bool*@

            <label>Custom Bool</label>

            <span>@Html.EditorFor(c => c.Active, "CustomBoolean")</span>

 

        </div>

    }

</fieldset>

 

The Custom editor template is

@model bool?

 

@Html.CheckBox("", Model.GetValueOrDefault())

 

The output looks like

clip_image001

The Solution in Visual Studio is something like

clip_image002

Displaying Dropdown in MVC

March 14, 2013

I could not have written this any better…. this is a copy from nerd dinner web site. The URL to their tutorial is http://nerddinnerbook.s3.amazonaws.com/Part6.htm

I’m copying it over so I don’t loose it if their site goes down or they move the link etc.

 

Passing Data from Controllers to View-Templates

One of the defining characteristics of the MVC pattern is the strict "separation of concerns" it helps enforce between the different components of an application. Models, Controllers and Views each have well defined roles and responsibilities, and they communicate amongst each other in well-defined ways. This helps promote testability and code reuse.

When a Controller class decides to render an HTML response back to a client, it is responsible for explicitly passing to the view template all of the data needed to render the response. View templates should never perform any data retrieval or application logic – and should instead limit themselves to only have rendering code that is driven off of the model/data passed to it by the controller.

Right now the model data being passed by our DinnersController class to our view templates is simple and straight-forward – a list of Dinner objects in the case of Index(), and a single Dinner object in the case of Details(), Edit(), Create() and Delete(). As we add more UI capabilities to our application, we are often going to need to pass more than just this data to render HTML responses within our view templates. For example, we might want to change the "Country" field within our Edit and Create views from being an HTML textbox to a dropdownlist. Rather than hard-code the dropdown list of country names in the view template, we might want to generate it from a list of supported countries that we populate dynamically. We will need a way to pass both the Dinner object and the list of supported countries from our controller to our view templates.

Let’s look at two ways we can accomplish this.

Using the ViewData Dictionary

The Controller base class exposes a "ViewData" dictionary property that can be used to pass additional data items from Controllers to Views.

For example, to support the scenario where we want to change the "Country" textbox within our Edit view from being an HTML textbox to a dropdownlist, we can update our Edit() action method to pass (in addition to a Dinner object) a SelectList object that can be used as the model of a countries dropdownlist.

view sourceprint?

01.

02.//

03.// GET: /Dinners/Edit/5

04.

05.[Authorize]

06.public ActionResult Edit(int id) {

07.

08. Dinner dinner = dinnerRepository.GetDinner(id);

09.

10. ViewData["Countries"] = new SelectList(PhoneValidator.AllCountries, dinner.Country);

11.

12. return View(dinner);

13.}

14.

The constructor of the SelectList above is accepting a list of counties to populate the drop-downlist with, as well as the currently selected value.

We can then update our Edit.aspx view template to use the Html.DropDownList() helper method instead of the Html.TextBox() helper method we used previously:

view sourceprint?

1.

2.<%= Html.DropDownList("Country", ViewData["Countries"] as SelectList) %>

3.

The Html.DropDownList() helper method above takes two parameters. The first is the name of the HTML form element to output. The second is the "SelectList" model we passed via the ViewData dictionary. We are using the C# "as" keyword to cast the type within the dictionary as a SelectList.

And now when we run our application and access the /Dinners/Edit/1 URL within our browser we’ll see that our edit UI has been updated to display a dropdownlist of countries instead of a textbox:

clip_image001

Because we also render the Edit view template from the HTTP-POST Edit method (in scenarios when errors occur), we’ll want to make sure that we also update this method to add the SelectList to ViewData when the view template is rendered in error scenarios:

view sourceprint?

01.

02.//

03.// POST: /Dinners/Edit/5

04.

05.[AcceptVerbs(HttpVerbs.Post)]

06.public ActionResult Edit(int id, FormCollection collection) {

07.

08. Dinner dinner = dinnerRepository.GetDinner(id);

09.

10. try {

11.

12. UpdateModel(dinner);

13.

14. dinnerRepository.Save();

15.

16. return RedirectToAction("Details", new { id=dinner.DinnerID });

17. }

18. catch {

19.

20. ModelState.AddModelErrors(dinner.GetRuleViolations());

21.

22. ViewData["countries"] = new SelectList(PhoneValidator.AllCountries, dinner.Country);

23.

24. return View(dinner);

25. }

26.}

27.

And now our DinnersController edit scenario supports a DropDownList.

Using a ViewModel Pattern

The ViewData dictionary approach has the benefit of being fairly fast and easy to implement. Some developers don’t like using string-based dictionaries, though, since typos can lead to errors that will not be caught at compile-time. The un-typed ViewData dictionary also requires using the "as" operator or casting when using a strongly-typed language like C# in a view template.

An alternative approach that we could use is one often referred to as the "ViewModel" pattern. When using this pattern we create strongly-typed classes that are optimized for our specific view scenarios, and which expose properties for the dynamic values/content needed by our view templates. Our controller classes can then populate and pass these view-optimized classes to our view template to use. This enables type-safety, compile-time checking, and editor intellisense within view templates.

For example, to enable dinner form editing scenarios we can create a "DinnerFormViewModel" class like below that exposes two strongly-typed properties: a Dinner object, and the SelectList model needed to populate the countries dropdownlist:

view sourceprint?

01.

02.public class DinnerFormViewModel {

03.

04. // Properties

05. public Dinner Dinner { get; private set; }

06. public SelectList Countries { get; private set; }

07.

08. // Constructor

09. public DinnerFormViewModel(Dinner dinner) {

10. Dinner = dinner;

11. Countries = new SelectList(PhoneValidator.AllCountries, dinner.Country);

12. }

13.}

14.

We can then update our Edit() action method to create the DinnerFormViewModel using the Dinner object we retrieve from our repository, and then pass it to our view template:

view sourceprint?

01.

02.//

03.// GET: /Dinners/Edit/5

04.

05.[Authorize]

06.public ActionResult Edit(int id) {

07.

08. Dinner dinner = dinnerRepository.GetDinner(id);

09.

10. return View(new DinnerFormViewModel(dinner));

11.}

12.

We’ll then update our view template so that it expects a "DinnerFormViewModel" instead of a "Dinner" object by changing the "inherits" attribute at the top of the edit.aspx page like so:

view sourceprint?

1.

2.Inherits="System.Web.Mvc.ViewPage<NerdDinner.Controllers.DinnerFormViewModel>

3.

Once we do this, the intellisense of the "Model" property within our view template will be updated to reflect the object model of the DinnerFormViewModel type we are passing it:

clip_image002

clip_image003

We can then update our view code to work off of it. Notice below how we are not changing the names of the input elements we are creating (the form elements will still be named "Title", "Country") – but we are updating the HTML Helper methods to retrieve the values using the DinnerFormViewModel class:

view sourceprint?

01.

02.<p>

03. <label for="Title">Dinner Title:</label>

04. <%= Html.TextBox("Title", Model.Dinner.Title) %>

05. <%=Html.ValidationMessage("Title", "*") %>

06.</p>

07.

08.<p>

09. <label for="Country">Country:</label>

10. <%= Html.DropDownList("Country", Model.Countries) %>

11. <%=Html.ValidationMessage("Country", "*") %>

12.</p>

13.

We’ll also update our Edit post method to use the DinnerFormViewModel class when rendering errors:

view sourceprint?

01.

02.//

03.// POST: /Dinners/Edit/5

04.

05.[AcceptVerbs(HttpVerbs.Post)]

06.public ActionResult Edit(int id, FormCollection collection) {

07.

08. Dinner dinner = dinnerRepository.GetDinner(id);

09.

10. try {

11. UpdateModel(dinner);

12.

13. dinnerRepository.Save();

14.

15. return RedirectToAction("Details", new { id=dinner.DinnerID });

16. }

17. catch {

18. ModelState.AddModelErrors(dinner.GetRuleViolations());

19.

20. return View(new DinnerFormViewModel(dinner));

21. }

22.}

23.

We can also update our Create() action methods to re-use the exact same DinnerFormViewModel class to enable the countries DropDownList within those as well. Below is the HTTP-GET implementation:

view sourceprint?

01.

02.//

03.// GET: /Dinners/Create

04.

05.public ActionResult Create() {

06.

07. Dinner dinner = new Dinner() {

08. EventDate = DateTime.Now.AddDays(7)

09. };

10.

11. return View(new DinnerFormViewModel(dinner));

12.}

13.

Below is the implementation of the HTTP-POST Create method:

view sourceprint?

01.

02.//

03.// POST: /Dinners/Create

04.

05.[AcceptVerbs(HttpVerbs.Post)]

06.public ActionResult Create(Dinner dinner) {

07.

08. if (ModelState.IsValid) {

09.

10. try {

11. dinner.HostedBy = "SomeUser";

12.

13. dinnerRepository.Add(dinner);

14. dinnerRepository.Save();

15.

16. return RedirectToAction("Details", new { id=dinner.DinnerID });

17. }

18. catch {

19. ModelState.AddModelErrors(dinner.GetRuleViolations());

20. }

21. }

22.

23. return View(new DinnerFormViewModel(dinner));

24.}

25.

And now both our Edit and Create screens support drop-downlists for picking the country.

Custom-shaped ViewModel classes

In the scenario above, our DinnerFormViewModel class directly exposes the Dinner model object as a property, along with a supporting SelectList model property. This approach works fine for scenarios where the HTML UI we want to create within our view template corresponds relatively closely to our domain model objects.

For scenarios where this isn’t the case, one option that you can use is to create a custom-shaped ViewModel class whose object model is more optimized for consumption by the view – and which might look completely different from the underlying domain model object. For example, it could potentially expose different property names and/or aggregate properties collected from multiple model objects.

Custom-shaped ViewModel classes can be used both to pass data from controllers to views to render, as well as to help handle form data posted back to a controller’s action method. For this later scenario, you might have the action method update a ViewModel object with the form-posted data, and then use the ViewModel instance to map or retrieve an actual domain model object.

Custom-shaped ViewModel classes can provide a great deal of flexibility, and are something to investigate any time you find the rendering code within your view templates or the form-posting code inside your action methods starting to get too complicated. This is often a sign that your domain models don’t cleanly correspond to the UI you are generating, and that an intermediate custom-shaped ViewModel class can help.

 

@Html.ActionLink overload(s) issue…

March 6, 2013

Came across an interesting minor issue today, so documenting it, in MVC to use the Html.ActionLink helper method, we simply use

@Html.ActionLink("Make Reservation", "RsvpForm")

To add custom attributes to the link, we have two overloads, one that expects an object and another that expects a IDictionary<string,object>. To use the one that uses the a object, we can simply do

@Html.ActionLink("Make Reservation", "RsvpForm", new { }, new { @class = "classme", temp = "tempme" })

Which outputs the following html

<a class="classme" href="/Home/RsvpForm" temp="tempme">Make Reservation</a>

Now to convert the object to the overload to a IDictionary overload. I simply swapped out the object with the Dictionary object as;

@Html.ActionLink("Make Reservation 2", "RsvpForm", new { }, new Dictionary<string, object> { { "class", "classme" }, { "temp", "tempme" } })

Which out puts the following html

<a Comparer="System.Collections.Generic.GenericEqualityComparer`1[System.String]" Count="2" Keys="System.Collections.Generic.Dictionary`2+KeyCollection[System.String,System.Object]" Values="System.Collections.Generic.Dictionary`2+ValueCollection[System.String,System.Object]" href="/Home/RsvpForm">Make Reservation 2</a>

 

The overloads of the helper class look like (the one I am interested in)

public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, object routeValues, object htmlAttributes);

 

public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, RouteValueDictionary routeValues, IDictionary<string, object> htmlAttributes);

So it seems like, when passing in an empty object for the route values and a Dictionary object to the ActionLink method, it uses the

public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, object routeValues, object htmlAttributes)

 

overload when I want it to use

public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, RouteValueDictionary routeValues, IDictionary<string, object> htmlAttributes)

So a slight adjustment to code makes everything work as expected. Either pass in a null for the routevalues or pass in a empty RouteValueDictionary object e.g

@Html.ActionLink("Make Reservation 3", "RsvpForm", new RouteValueDictionary(), new Dictionary<string, object> { { "class", "classme" }, { "temp", "tempme" } })

<br />

@Html.ActionLink("Make Reservation 4", "RsvpForm", null, new Dictionary<string, object> { { "class", "classme" }, { "temp", "tempme" } })

And the html generated for either one is identical

<a class="classme" href="/Home/RsvpForm" temp="tempme">Make Reservation 3</a>

        <br />

<a class="classme" href="/Home/RsvpForm" temp="tempme">Make Reservation 4</a>

 

Slight ignorance on my part, but never the less it was a fun fact to come across.

 

Create your own website, free on WordPress.com.Create your own website.
Start free