genxgeek
genxgeek

Reputation: 13347

Anonymous types object creation and passed into MVC# razor view?

Q1: What is better shorthand version of the following? Q2: How can I pass anonymous types to my view in mvc3?

    public ViewResult Index3()
    {
        List<T1> ls = new List<T1>();
        ls.Add(new T1 { id = 1, title = "t1", val1 = 1, val2 = 2});
        ls.Add(new T1 {id=2, title="t2", val1=3, val2=4});
        ls.Add(new T1 { id = 3, title = "t3", val1 = 5, val2 = 6});

        return View(ls);
    }

(Q1) Something similar to?:

        List<T1> ls = new List<T1>(
            List<T1>(new { id = 1, title = "t1", val1 = 1, val2 = 2}
            new { id = 2, title = "t2", val1 = 3, val2 = 4})
        );

(Q2) Something similar to?:

    public ViewResult Index3()
    {                           
        return View(List(new { id = 1, title = "t1", val1 = 1, val2 = 2 }
            new { id = 2, title = "t2", val2 = 3, val2 = 4 }
        );
    }

Then reference the above in the razor view:

    @model IEnumerable<Some Anonymous or Dynamic Model>

    @item.id
    @item.title
    @item.val1
    ...

Upvotes: 0

Views: 749

Answers (4)

jbtule
jbtule

Reputation: 31799

Neither option will work as anonymous types are internal and razor views are compiled into a separate assembly.

See: Dynamic view of anonymous type missing member issue - MVC3

Upvotes: 0

SLaks
SLaks

Reputation: 887375

  1. Collection initializers are written like this:

    List<T1> ls = new List<T1> {
        new T1 { id = 1, title = "t1", val1 = 1, val2 = 2 },
        new T1 { id = 2, title = "t2", val1 = 3, val2 = 4 },
        new T1 { id = 3, title = "t3", val1 = 5, val2 = 6 }
    };
    
  2. Create an implicitly-typed array:

    return View(new [] { new { id = 1, ... }, ... });
    

Upvotes: 0

Deekane
Deekane

Reputation: 143

Could use ViewBag to pass your list to the view.

Upvotes: 1

Erik Funkenbusch
Erik Funkenbusch

Reputation: 93424

Q1 is a matter of preference. There is no performance difference as the compiler internally creates similar code.

Q2 is impossible, you must create a non-anonymous type to be able to access it.

Upvotes: 1

Related Questions