0

Question: How could I rewrite the anonymous type syntax in the ActionLink to be a little more standard OOP? I'm trying to understand what is happening.

What I think it means is: Creating an object with a single property id, which is an int, equal to that of the DinnerID in item, which is a Dinner.

 <% foreach (var item in Model) { %>

        <tr>
            <td>
                <%: Html.ActionLink("Edit", "Edit", new { id=item.DinnerID }) %> |
                <%: Html.ActionLink("Details", "Details", new { id=item.DinnerID })%> |
                <%: Html.ActionLink("Delete", "Delete", new { id=item.DinnerID })%>
            </td>
            <td>
                <%: item.DinnerID %>
            </td>
            <td>
                <%: item.Title %>
            </td>

I think I get Anonymous types: Wrote what I think is happening under the hood.

class Program
    {
        static void Main(string[] args)
        {
            // Anonymous types provide a convenient way to encapsulate a set of read-only properties
            // into a single object without having to first explicitly define a type
            var person = new { Name = "Terry", Age = 21 };
            Console.WriteLine("name is " + person.Name);
            Console.WriteLine("age is " + person.Age.ToString());

            Person1 person1 = new Person1("Bill",55);
            Console.WriteLine("name is " + person1.Name);
            Console.WriteLine("age is " + person1.Age.ToString());

            //person1.Name = "test"; // this wont compile as the setter is inaccessible
        }
    }

    class Person1
    {
        public string Name { get; private set; }
        public int Age { get; private set; }

        public Person1(string name, int age)
        {
            Name = name;
            Age = age;
        }
    }

Many thanks.

2
  • Absolutely nothing wrong with anonymous types. Why bother creating a class that has 1 property,id.? This is what anonymous types are best for. Commented Jun 23, 2010 at 3:04
  • 1
    Either method (anon or named class) works. The MVC framework is just using reflection to get the property names/values anyway. Commented Jun 23, 2010 at 4:31

1 Answer 1

2

That's pretty much what it's doing except that the properties of anonymous types have public setters, and the anonymous types have parameterless constructors.

So a more accurate equivalent would be:

class Person1 
{ 
    public string Name { get; set; } 
    public int Age { get; set; } 
}

Person1 person1 = new Person1 { Name = "Bill", Age = 55 };
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.