Using two entitades in the same View

Asked

Viewed 2,076 times

0

I have a table, where I return the vacation records of each employee, and I need to create a page, where the user can request the change of this period. However, the demand requires that the data be in the same "table". Therefore, I need to do a foreach in the holiday table, and put the change fields(table requirement) in the same view.

This image exemplifies the final result I need to obtain. inserir a descrição da imagem aqui

In this case, the Start Date and End Date belong to the vacation class, and the rest to the requirement class. My demand is that the user click edit, the table enable the fields Initial date change and final date change, for the user to put the dates you want, and so I save this data in the database, in the table requirement.

In the database, I return the "Start Date and End Date" data from a View, called Vacation, and the "Start Date Change and End Date Change" data must be saved in a table called Requirements.

I don’t know how I can do it, if I use Viewmodel, javascript, Jquery, etc.

Saving method:

[HttpPost]
        public ActionResult Ferias(Requerimento requerimento)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    requerimento.sLotacao = SessionHelper.Lotacao;
                    requerimento.sNome = SessionHelper.Nome;
                    if (SessionHelper.Celular == null || SessionHelper.Celular == " ")
                    {
                        requerimento.sTelefone = SessionHelper.Telefone;
                    }
                    else
                    {
                        requerimento.sCelular = SessionHelper.Celular;
                    }

                    requerimento.sEndereco = SessionHelper.Endereco;
                    requerimento.sEmail = SessionHelper.Email;
                    requerimento.sVinculo = SessionHelper.Vinculo;
                    requerimento.sCargo = SessionHelper.Cargo;
                    requerimento.dtDataRequerimento = DateTime.Now;
                    requerimento.iMatricula = SessionHelper.Matricula;
                    requerimento.sSituacao = "Aberto";
                    requerimento.sTipoRequerimento = "Ferias";
                    requerimentosRepository.Inserir(requerimento);
                    TempData["Mensagem"] = "Requerimento cadastrado com sucesso";
                }
                catch (Exception ex)
                {
                    TempData["Mensagem"] = ex.Message;

                }
                return RedirectToAction("MeusRequerimentos");
            }
            var errors = ModelState.Values.SelectMany(v => v.Errors);
            Debug.Write(errors);
            return View(requerimento);
        }

View:

@model IEnumerable<PortalRH.DomainModel.Entities.FuncionariosFerias>

@{
    ViewBag.Title = "Minhas Férias";
}

<div class="Nome">
    <p><strong><font face="Arial" size="2"> @ViewBag.Matricula / @ViewBag.Contrato - @ViewBag.Nome</font></strong></p>
</div>
<div class="mapLocal">
    <img src="~/Content/img/sitemap.ico" width="19" height="19" /> Você está em: <i>@ViewBag.Title</i>
</div>
<br />
<div class="row">
    <div class="col-md-2">

    </div>
    <div class="col-md-8">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h5><strong>Férias</strong></h5>
            </div>

            <table class="table table-condensed">
                <tr>
                    <th>Inicio Férias</th>
                    <th>Fim Férias</th>
                    <th>Inicio Férias Alteração</th>
                    <th>Fim Férias Alteração</th>
                    <th></th>
                </tr>
                @foreach (var item in Model)
                {
                    <tr>
                        <td>@Html.DisplayFor(modelItem => item.DtInicioPeriodo)</td>
                        <td>@Html.DisplayFor(modelItem => item.DtFimPeriodo)</td>
                        <td>@Html.DisplayFor(modelItem => item.DtInicioAlteracao)</td>
                        <td>@Html.DisplayFor(modelItem => item.DtFimAlteracao)</td>
                        <td>Editar</td>
                    </tr>
                }
            </table>
            </div>
        </div>
    </div>
  • You can always create two fields [NotMapped] (one for the initial change date and one for the end date) in the holiday class, to fill in the values that are in the requirement class. To save the data, in the controller, just fetch the returned value from the view and save the data in the required class

  • @Cesarmiguel edited the question with my method to save, would help in how I take the values to use in the controller?

  • You can use a Viewmodel

  • Yeah, or use a Viewmodel. You have both tables with some connection, right? Foreign key or something

  • @Cesarmiguel do not have, because the Holiday table is a View in Sql, I do not have access to the table itself, only to View.

  • Explain it better, you have two tables right? One with the Initial and Final Date, and one with the Initial Date Change and Final Date Change. Am I right? What is called each of these tables?

  • @Cesarmiguel, exactly that. I edited with the names of each table

  • @Renilsonandrade, do you have the holiday table and request? I’m sorry but that’s what I keep reading the question

  • I have View Vacations and Table requirement

Show 4 more comments

1 answer

4


You can create a single Viewmodel that includes the Holiday and Requirement information you want to save.

Viewmodel represents a set of one or more Models and other data that will be represented in a View that needs to display a certain set of information.

Example:

public class SeuViewModel
{
   //Todas as propriedade que você deseja utilizar na View

   //Informações de Férias...
   public int IdFerias { get; set; }
   public string DtInicioPeriodo { get; set; }
   public string DtFimPeriodo { get; set; }

   //Informações de Requerimento...
   public int IdRequerimento { get; set; }
   public string DtInicioAlteracao { get; set; }
   public string DtFimAlteracao { get; set; }
}

Your View must be typed according to your Model so you can access all information:

@model ...SeuViewModel

<html>
    <body>
        @using (Html.BeginForm())
        {
            ...               
        }
    </body>
</html>

In your Controller, your Post action will receive an object from your Model:

[HttpGet]
public ActionResult Ferias(SeuViewModel seuViewModel)
{
    if (ModelState.IsValid)
    {

        //Através do objeto seuViewModel, você obtem os dados informados 
        //e monta os objetos que deseja salvar.      

        ...
        var ferias = seu_repositorio.ObterFeriasPorId(seuViewModel.IdFerias);
        ferias.DataInicio = seuViewModel.DtInicioPeriodo;
        ferias.DataFim = seuViewModel.DtIFimPeriodo;

        var requerimento = seu_repositorio.ObterRequerimentoPorId(seuViewModel.IdRequerimento);
        requerimento.DataInicioAlteracao = seuViewModel.DtInicioAlteracao;
        requerimento.DataFimAlteracao = seuViewModel.DtFimAlteracao;
        ...
    } 
    ...
}

If it is a holiday "list" and requirements you still have your Viewmodel, but can create others to be used within it, example:

public class SeuViewModel
{
   //Todas as propriedade que você deseja utilizar na View
   ...
   public IList<FeriasViewModel> { get; set; }
   public IList<RequerimentoViewModel> { get; set; }       
}

public class FeriasViewModel
{
   //Informações de Férias...
   public int IdFerias { get; set; }
   public string DtInicioPeriodo { get; set; }
   public string DtFimPeriodo { get; set; }
}

public class RequerimentoViewModel
{
   //Informações de Requerimento...
   public int IdRequerimento { get; set; }
   public string DtInicioAlteracao { get; set; }
   public string DtFimAlteracao { get; set; }
}

Your View remains typed according to your Model so you can access all information, example:

@model ...SeuViewModel

<html>
    <body>
        @using (Html.BeginForm())
        {
            ...      
            @foreach (var item in Model.Ferias)
            {
                <tr>
                    <td>@Html.HiddenFor(modelItem => item.IdFerias)</td>
                    <td>@Html.DisplayFor(modelItem => item.DtInicioPeriodo)</td>
                    <td>@Html.DisplayFor(modelItem => item.DtFimPeriodo)</td>
                    <td>Editar</td>
                </tr>
            }

            ...      
            @foreach (var item in Model.Requerimentos)
            {
                <tr>
                    <td>@Html.HiddenFor(modelItem => item.IdRequerimento)</td>
                    <td>@Html.DisplayFor(modelItem => item.DtInicioPeriodo)</td>
                    <td>@Html.DisplayFor(modelItem => item.DtFimPeriodo)</td>
                    <td>Editar</td>
                </tr>
            }
            ...       
        }
    </body>
</html>

In your Controller, your Post action continues to receive an object from your Model. You will receive vacation lists and requirements and save them:

[HttpGet]
public ActionResult Ferias(SeuViewModel seuViewModel)
{
    if (ModelState.IsValid)
    {

        //Através do objeto seuViewModel, você obtem os dados informados 
        //e monta os objetos que deseja salvar.      

        ...
        foreach (var item in seuViewModel.Ferias)
        {
           var ferias = seu_repositorio.ObterFeriasPorId(item.IdFerias);
           ferias.DataInicio = seuViewModel.DtInicioPeriodo;
           ferias.DataFim = seuViewModel.DtIFimPeriodo;
        }

        foreach (var item in seuViewModel.Requerimentos)
        {
           var requerimento = seu_repositorio.ObterRequerimentoPorId(seuViewModel.IdRequerimentos);
           requerimento.DataInicioAlteracao = seuViewModel.DtInicioAlteracao;
           requerimento.DataFimAlteracao = seuViewModel.DtFimAlteracao;
        ...
    } 
    ...
}
  • 1

    The answer was helpful?

Browser other questions tagged

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