View with 2 model inside a Viewmodel

Asked

Viewed 617 times

1

Goal: Manipulate 2 model in the view using a Viewmodel.

I made a Viewmodel to encapsulate the 2 models, but I can’t use one of them.

Viewmodel:

public class BoletoConfigViewModel
{
    public Boleto Boletos { get; set; }
    public ConfigCliente Config { get; set; }
}

Controller:

    var config = db.Config
        .SingleOrDefault(x => x.ClienteId == 3); //consulta com o DataBase

//I’m not sure that would be the best way for this consultation.

    var viewModel = new BoletoConfigViewModel
    {
        Boletos = new Boleto(),
        Config = config
    };

    return View(viewModel);

In view:

@model WMB.MVC.Extranet.ViewModel.BoletoConfigViewModel

@using (Html.BeginForm()) 
{
   @Html.AntiForgeryToken()
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Boletos.DataVencimento, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Boletos.DataVencimento, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Boletos.DataVencimento, "", new { @class = "text-danger" })
            </div>
        </div>

..//bastante codigo acima criado pelo Scanffolding...
Agora onde da problema
<div>Configuração.:</div> @Html.DisplayFor(model => model.Config.cur_Configuracao.ToString());

I was told to do with a partial view, etc... But for learning purposes and imagining that elsewhere I will need this is not possible?

Error:

Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions
Riga 85:     <div>Configuração.:</div> @Html.DisplayFor(model => model.Config.cur_Configuracao.ToString());

1 answer

3


The message is quite clear:

Templates can be used only with field access, Property access, single-Dimension array index, or single-Parameter custom indexer Expressions.

I mean, you can only use @Html.DisplayFor with:

  • Common class variables;
  • Estates;
  • Arrays with a dimension;
  • Parameters with a dimension indexer.

In case you used .ToString(), which is neither: it is a method.

There are some options you can use:

1. The property without the .ToString():

@Html.DisplayFor(model => model.Config.cur_Configuracao)

2. Removing the @Html.DisplayFor:

@Model.Config.cur_Configuracao.ToString()
  • But if the property (in my decimal case) I can have it shown on the screen ? I thought only string could show on the screen.

  • You can. No problem at all.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.