Willy
Willy

Reputation: 10638

Access a custom model from the view

I am using asp.net MVC 4 and razor syntax. I have a custom model, imagine this:

namespace MyProject.SampleModel
{
    public class MyCustomModel
    {
        public bool MyBoolean1 { get; set; }
        public bool MyBoolean2 { get; set; }
    }
}

so from the view, in the header, I do:

@model MyProject.SampleModel.MyCustomModel

(...)
@Html.CheckBoxFor(m => m.MyBoolean1 ) <---- ERROR HERE: MyBoolean1 is not recognized
(...)

But in line CheckBoxFor, in the lambda, my MyBoolean1 is not recognized. Why?

First attempt:

It seems like replacing

@model MyProject.SampleModel.MyCustomModel 

with:

@using MyProject.SampleModel 

there are no compilation errors but in runtime an error is raised:

Compiler Error Message: CS1963: An expression tree may not contain a dynamic operation

Upvotes: 0

Views: 254

Answers (1)

Marco
Marco

Reputation: 23937

replace

@using MyProject.SampleModel 

with

@model MyProject.SampleModel.MyCustomModel

As the error states, lambda expressions do not support dynamic models. By defining the model you are strongly typing it.

Using your faulty statement, you are referencing just a namespace, which will per se work, if you elimenate your lambda expressions from the code, but you won't have a strongly typed view any longer.

Kind regards

//EDIT:

We found out, that the core of the question is: how to use 2(3, 4, 5 ... n) models in one view.

Lets assume you have model 1:

public class MyCustomModel
{
    public bool MyBoolean1 { get; set; }
    public bool MyBoolean2 { get; set; }
}

And model 2:

public class SecondModel
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

You need to create a third class which combines these two models.

public class ExampleViewModel
{
    public MyCustomModel BoolValues { get; set; }
    public SecondModel Names { get; set; }
}

Now you just return an ExampleViewModel to your view in your controller action and use

@model MyProject.SampleModel.ExampleViewModel

and access your properties in this way:

@foreach (var item in Model.BoolValues)
{
    <div>@item.Myboolean1</div>
}

@foreach (var item in Model.Names)
{
    <div>@item.FistName</div>
}

Upvotes: 1

Related Questions