Obtain controller object in the view

1

as I do to obtain and manipulate an object that returned with the view from the controller. this is the code

public ActionResult CargarDiesel(int id)
    {
        var equipo = (from eq in db.equipos
                      join cd in db.cargasDiesel on eq.id equals cd.equiposId
                      where eq.id == id
                      select new { eq, cd });
        return View(equipo);
    }
    
asked by German Ortiz 21.08.2017 в 19:43
source

1 answer

0

First you have to tell your view with what model you are working with, for this you define the model with Razor in the following way:

@using TuNamespace.Models
@model TuNamespace.Models.TuObjeto

The first line is to access the namespace where your models are located (or the model you want to access) the second line is the one that tells the View that will work with that specific model.

From there @Model will contain the object that you returned from the controller, to access its properties is as easy as doing @Model.Propiedad and you can use it as you would use any variable in Razor

<h1>Id: @Model.Id</h1>

Update

In case you do not have a model for the object that is returned from the controller, the simplest way to solve it is to create a ViewModel that is not more than a class that contains the properties that you will use in your View . The use is the same, you only have to change the first lines to look for ViewModel instead of Model and it would be something like this:

@using TuNamespace.ViewModels
@model TuNamespace.ViewModels.TuViewModel
    
answered by 21.08.2017 / 20:08
source