Home > Software engineering >  ASP.NET MVC View can't see member of an anonymous object viewModel
ASP.NET MVC View can't see member of an anonymous object viewModel

Time:02-08

I am trying to create an anonymous object view model with one member being from the Models folder, and another being from my own custom classes folder:

var viewModel = new {
    test1 = new Models.Test1(),
    test2 = new Classes.Test2()
};

return View(viewModel);

In the view, @Model, if you pause/breakpoint, and inspect it with the Visual Studio debugger, contains:

Model [press enter]:

{ Test1 = {MVC_Test1.Models.Test1}, Test2 = {MVC_Test1.Classes.Test2} }
    Test1: {MVC_Test1.Models.Test1}
    Test2: {MVC_Test1.Classes.Test2}

However, if you try the following:

Model.Test1 [press enter]

'Model.Test1' threw an exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException'
Message: "'object' does not contain a definition for 'Test1'"

What is wrong? Is there a way to refer to a dynamically created view model done this way? Or must I explicitly create a class that instantiates Models.Test1() and Classes.Test2() into one class, and use that instead of the anonymous object?

CodePudding user response:

there is no sense in anonymous model for view, since you will have to create a anomymous input controls, so create a real typed view model

public class ViewModel
{   
public Test1 Test1 {get; set;}
public Test2 Test2 {get; set;}  
};

model  = new ViewModel {
    test1 = new Models.Test1(),
    test2 = new Classes.Test2()
};

return View(model);
````
  •  Tags:  
  • Related