Send view value to C# ASP NET MVC controller

Asked

Viewed 288 times

2

I need to pass an ID of a forach inside a form of my view to the controller, but I couldn’t find the best way to do it.

I tried to call a Hiddenfor with the ID in the foreach or call the value by Formcollection, but I did not get concrete results in either case. Someone would have the best solution?

view:

@using (Html.BeginForm("AdicionaGestor", "Ti01", FormMethod.Post))
{
    <!-- Modal Gestor -->
    <div class="modal fade" id="ModalGestor" role="dialog">
        <div class="modal-dialog">

            <!-- Modal content-->
            <!--Passa parametro CadastroID para o controller-->
            @Html.HiddenFor(model => model.CadastroID, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title text-left">Adicionar um gestor a solicitação</h4>
                </div>
                <div class="modal-body">
                    @Html.EditorFor(model => model.UsuarioGestor, new { htmlAttributes = new { @class = "form-control" } })

                    <p>Selecione o recurso que você deseja atrelar a este gestor:</p>
                    <br />

                    @foreach (var item in (List<Ti01Model>)TempData["TarefasInfra"])
                    {
                        @Html.RadioButtonFor(model => model.RecursoGestor, item.Recursos)
                        <label for="@Html.DisplayFor(modelItem => item.Recursos)">@Html.DisplayFor(modelItem => item.Recursos)</label>

                        <!--Passa parametro IdRecurso para o controller-->
                        @Html.HiddenFor(model => item.IdRecurso, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
                        <br />
                    }

                    @foreach (var item in (List<Ti01Model>)TempData["TarefasSistemas"])
                    {
                        @Html.RadioButtonFor(model => model.RecursoGestor, item.Recursos)
                        <label for="@Html.DisplayFor(modelItem => item.Recursos)">@Html.DisplayFor(modelItem => item.Recursos)</label>

                        <!--Passa parametro IdRecurso para o controller-->
                        @Html.HiddenFor(model => item.IdRecurso, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
                        <br />
                    }

                    <br />
                    <br />
                    @Html.TextAreaFor(model => model.ObsAddGestor, new { @class = "form-control", rows = "4", cols = "4" })

                </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>
                        <button type="submit" class="btn btn-success">Adicionar</button>
                    </div>
                </div>

        </div>
    </div>
}

controller:

public ActionResult AdicionaGestor(Ti01Model model)
        {
            HttpCookie CookieNomeCompleto = System.Web.HttpContext.Current.Request.Cookies.Get("NomeCompleto");
            HttpCookie CookieUsuario = System.Web.HttpContext.Current.Request.Cookies.Get("usuario");
            HttpCookie CookieGestor = System.Web.HttpContext.Current.Request.Cookies.Get("gestor");
            String usuario = CookieUsuario.Value;
            String nome = CookieNomeCompleto.Value;

            Ti01Dal dal = new Ti01Dal();
            AuthoAD ad = new AuthoAD();
            Ti01 t = new Ti01();

            t.CadastroID = model.CadastroID;
            t.IdRecurso = t.IdRecurso;
            t.UsuarioGestor = model.UsuarioGestor;
            t.NomeGestor = ad.RetornaUserInfoAD(t.UsuarioGestor).Nome;
            t.EmailGestor = ad.RetornaUserInfoAD(t.UsuarioGestor).Email;
            t.RecursoGestor = model.RecursoGestor;

            t.UsuarioMov = usuario;
            t.Observacao = "Adicionou " + t.NomeGestor + "(" + t.UsuarioGestor + ")" + " como gestor/aprovador para a tarefa:" + t.RecursoGestor;

            try
            {

                //ADICIONA O GESTOR NA TABELA TI01E
                dal.AdicionaGestor(t);

                ////ENVIO DE EMAIL - NOTIFICAÇÃO
                //if (dal.VerificaAprovacoes(t.CadastroID) == 2)
                //{
                //    EmailSolicitacaoAprovada(t);
                //}


                GetUser();
                GetUnidades();
                GetCargos();
                GetCentrosCusto();
                ModelState.Clear();

                //return View("Acompanhamento", new { id = model.CadastroID });
                return RedirectToAction("Acompanhamento", "Ti01", new { id = t.CadastroID });


            }
            catch (Exception ex)
            {

                throw new Exception(ex.Message);
            }
        }
  • Need to pass on what kind of action?

  • @Lucas Uma Actionresult

  • You want to post a list of ids?

  • Use this ID to popular a record in the database

  • The ideal would be to pass this ID as a model, but by putting this in the foreach, it returns null to the controller.

  • Put an example of your controller.

  • Added controller.

  • Your controller method ta receiving the Ti01model object, but apparently your view is sending another object. When you do Submit, you want to send the ids that are in the 2 foreach?

  • In the view I am using Radio Buttons, so just have to select an option (1 ID)

  • The foreach is there to print two different lists

  • Got it. The way your controller is, it only takes one object, you have to change it to List<Ti01model>. Otherwise, you will need to make modifications to the view so you can send a list of Ti01model in a single post

  • For this case, I find it simpler to make a post with some javascript library, it can be jQuery, for example. To do with the Razor, it becomes complex, laborious and difficult to maintain.

  • With Razor is simpler in cases where Voce updates 1 record per request. When Voce wants to send multiple records in a single request, it is worth considering the call by some javascript library.

  • How it would be done by jQuery, for example?

  • There is already a solution for this: https://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx/

Show 10 more comments
No answers

Browser other questions tagged

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