How to pass more than one parameter to a Controller?

Asked

Viewed 160 times

2

I am in need of a backup to pass more than one parameter to a Creation Controller. I have some models as below:

  • Usuario : Brings the information of the user who opened the call ex. id_usuario, username
  • Chamado : Brings the title, content, user’s id_name, date, etc
  • Evolucao : Contains id_evolucao, id_chamado, id_usuario, Texto_evolucao

When I create a new evolution I need to pass to the Controller the id_chamado (defining the call to which it belongs) and also the id_usuario (creator of the evolution of the call), in addition to other information.

What is the most practical way to implement this feature?

  • What is a creation controller? I searched the internet but found nothing about it. Where are you having problems? In the URL call? " I will create a new evolution": What is evolution?

1 answer

2

The right way is by using Viewmodel:

namespace SeuProjeto.ViewModels
{
    public class CriarEvolucaoViewModel
    {
        public Usuario Usuario { get; set; }
        public Chamado Chamado { get; set; }
        public Evolucao Evolucao { get; set; }
    }
}

In the Action GET, you will have to bring all possible records and initialize the object Viewmodel:

    public async Task<ActionResult> Create()
    {
        ViewBag.UsuariosPossiveis = db.Usuarios.ToList();
        ViewBag.ChamadosPossiveis = db.Chamados.ToList();
        return View(new CriarEvolucaoViewModel 
        {
            Usuario = new Usuario(),
            Chamado = new Chamado(),
            Evolucao = new Evolucao()
        });
    }

View:

@model SeuProjeto.ViewModels.CriarEvolucaoViewModel
@using SeuProjeto.Models

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>


@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Evolucao</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Usuario, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.Usuario.UsuarioId, 
                    ((IEnumerable<Usuario>)ViewBag.UsuariosPossiveis).Select(option => new SelectListItem 
                {
                    Text = option.Nome,
                    Value = option.UsuarioId.ToString()
                }),
                new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.Usuario.UsuarioId, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Chamado, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.Chamado.ChamadoId, 
                    ((IEnumerable<Usuario>)ViewBag.ChamadosPossiveis).Select(option => new SelectListItem 
                {
                    Text = option.Titulo,
                    Value = option.ChamadoId.ToString()
                }),
                new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.Chamado.ChamadoId, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Texto, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.TextAreaFor(model => model.Texto, new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.Texto, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

To Action of Controller who will receive it is something like this:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Create(CriarEvolucaoViewModel viewModel)
    {
        if (ModelState.IsValid)
        {
            // Aqui você pode fazer verificações adicionais, se quiser.

            var novaEvolucao = new Evolucao
            {
                EvolucaoId = Guid.NewGuid(),
                Usuario = db.Usuarios.Single(u => u.UsuarioId == viewModel.Usuario.UsuarioId),
                Chamado = db.Chamados.Single(c => c.ChamadoId == viewModel.Chamado.ChamadoId),
            }

            db.Evolucoes.Add(novaEvolucao);
            await db.SaveChangesAsync();
            return RedirectToAction("Index");
        }

        return View(viewModel);
    }

The advantage of this method is that you can create as well Usuario and Chamado on the same screen, only putting the fields appropriately and modifying the insertion logic.

If you won’t enter Usuario and Chamado, You can make it simpler:

    public async Task<ActionResult> Create()
    {
        ViewBag.UsuariosPossiveis = db.Usuarios.ToList();
        ViewBag.ChamadosPossiveis = db.Chamados.ToList();
        return View();
    }

View:

@model SeuProjeto.Models.Evolucao
@using SeuProjeto.Models

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>


@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Evolucao</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Usuario, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.UsuarioId, 
                    ((IEnumerable<Usuario>)ViewBag.UsuariosPossiveis).Select(option => new SelectListItem 
                {
                    Text = option.Nome,
                    Value = option.UsuarioId.ToString()
                }),
                new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.UsuarioId, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Chamado, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.ChamadoId, 
                    ((IEnumerable<Usuario>)ViewBag.ChamadosPossiveis).Select(option => new SelectListItem 
                {
                    Text = option.Titulo,
                    Value = option.ChamadoId.ToString()
                }),
                new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.ChamadoId, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Texto, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.TextAreaFor(model => model.Texto, new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.Texto, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Action POST:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Create([Bind(Include = "ChamadoId,UsuarioId,Texto")]Evolucao evolucao)
    {
        if (ModelState.IsValid)
        {
            // Aqui você pode fazer verificações adicionais, se quiser.

            db.Evolucoes.Add(evolucao);
            await db.SaveChangesAsync();
            return RedirectToAction("Index");
        }

        return View(evolucao);
    }
  • Hello Gypsy, I made the implementation according to your suggestion and was cool. However, the attributes of id_usuario and id_chamado were 0 in the Create bind (when debugging I could see this information). Theoretically wasn’t he supposed to receive these values from the view? What can I be forgetting to do?

  • Which of the approaches you used?

  • I used the second approach, but it also brings me the possibility to choose not only the call but the user who will make the evolution (through the dropdowns). What I seek is precisely to make evolutions in a call (selected in a previous list) and to see the history of its evolutions, to be able to make new interactions for the specific call. With this, the user who is authenticated in the current session and also the current call should be linked to the evolution. Another observation is that the way I implemented following your guidelines, when I submit the form only the text

  • evolution is passed to the controler (both the id_user and the namedid_) are going with the value 0.

  • People who have read this approach.. do you have any suggestions?... I continue with this difficulty.

  • @Marceloalmeida Update your question with what has been implemented, please.

Show 1 more comment

Browser other questions tagged

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