How can I make a Vista pass a ListModels to a controller? One of the fields of the Model is loaded by the user in the view

0

I have a view that corresponds to a survey. It is loaded with the questions and at the same time in the last column has a DropDowList with the possible answers. The problem I have is that I can not get my controller to receive the data of the questions and answers.

View:

 @using (Html.BeginForm("CompetenciasEspecificas", "VDTCabecera",Model, 
FormMethod.Get, new { @class = "form-horizontal" }))
{
<div id="block1">
    <fieldset>

        <legend class="text-center header">Competencias Cardinales</legend>
        <legend class="text-center header">@ViewBag.Message</legend>
    </fieldset>
</div>

<table class="table" style="table-layout:fixed">
    <tr>
        <th width="50" height="16">
            @Html.DisplayNameFor(model => model.Item)
        </th>
        <th width="200" height="16">
            @Html.DisplayNameFor(model => model.Descripcion)
        </th>
        <th width="100" height="16"></th>

    </tr>

    @foreach (var item in Model)
    {

    <tr>
        <td>
            <b>@Html.DisplayFor(modelItem => item.Item)</b>
        </td>
        <td>
            <p>@Html.DisplayFor(modelItem => item.Descripcion)</p>
        </td>
        <td>
            @{
        List<SelectListItem> listItems = new List<SelectListItem>();
        listItems.Add(new SelectListItem
        {
            Text = "4 (Grado Alto)",
            Value = "4",
            Selected = true
        });
        listItems.Add(new SelectListItem
        {
            Text = "3 (Bueno por encima del estandar)",
            Value = "3"

        });
        listItems.Add(new SelectListItem
        {
            Text = "2 (Minimo necesario para el puesto)",
            Value = "2"

        });

        listItems.Add(new SelectListItem
        {
            Text = "1 (Insatisfactorio)",
            Value = "1"

        });
            }

            <div class="form-group">
                <div class="col-md-10">
                    @Html.DropDownListFor(modelItem => item.Calificacion, listItems, null, htmlAttributes: new { @class = "form-control", Title = "Estado en el cual se encuentra la parametrización actual" })
                    @Html.ValidationMessageFor(modelItem => item.Calificacion, "", new { @class = "text-danger" })
                </div>
            </div>
        </td>
    </tr>

    }

</table>



<div class="form-group">
    <div class="col-md-12 text-center">
        <input type="submit" value="Siguiente página" class="btn btn-primary btn-lg" />
    </div>
</div>
}

Controller:

public ActionResult CompetenciasEspecificas(List<VDTAnalisisHabReqModel> collection)        
    {
        try
        {
            // TODO: Add insert logic here
            if (ModelState.IsValid)
            {




                HabilidadesRequeridasServices srvhab = new HabilidadesRequeridasServices();
                List<VDTAnalisisHabReqModel> list = new List<VDTAnalisisHabReqModel>();
                /*
                foreach (VDTAnalisisHabReqModel a in collection)
                {
                    srvhab.InsertarDetalleHabilidad(a);
                }
                */

                /*list = srvhab.ObtenerHabilidadesEspecificas(collection[0].FuncionarioId);

                for (int i = 0; i < list.Count; i++)
                {
                    list[i].DatosFuncionario = collection[0].DatosFuncionario;
                    list[i].VdtId = collection[0].VdtId;
                }


                ViewBag.Message = collection[0].DatosFuncionario;*/

                return View(list);

            }

            return View();
        }
        catch
        {
            return View();
        }
    }
    
asked by Elizardo Rodriguez 13.03.2018 в 14:49
source

3 answers

0

I personally would do it with Ajax so I can build my model and send it without problems.

I hope you serve

Table

<table id="tbl" style="width:100%" border="1">
      <thead>
        <tr>
        <th>item</th>
        <th>Descripción</th>
        <th>
          Opción
        </th>
      </tr>
      </thead>
      <tbody>
      <tr>
        <td>1</td>
        <td>Descripcion item 1</td>
        <td>
          <select>
            <option value="1">1 (Insatisfactorio)</option>
            <option value="2">2 (Minimo necesario para el puesto)</option>
            <option value="3">3 (Bueno por encima del estandar)</option>
            <option value="4">4 (Grado Alto)</option>
          </select>
        </td>
      </tr>
      <tr>
        <td>2</td>
        <td>Descripcion item 2</td>
        <td>
          <select>
            <option value="1">1 (Insatisfactorio)</option>
            <option value="2">2 (Minimo necesario para el puesto)</option>
            <option value="3">3 (Bueno por encima del estandar)</option>
            <option value="4">4 (Grado Alto)</option>
          </select>
        </td>
      </tr>
      </tbody>
    </table>

The ActionResult changes to the controller via JsonResult. It would be as follows.

Driver

[HttpPost]
public JsonResult CompetenciasEspecificas(SampleViewModel[] collection)
{                       
    return Json(new { model = collection});
}

Javascript

$("form").submit(function(e){
   e.preventDefault();

   var modelArr = []; // Arra que se enviara al controlador

   $('#tbl tbody tr').each(function(){
      // Por cada row de la table   
   var obj = {
        Prop1: $(this).children('td').eq(0).text(),
        Prop2: $(this).children('td').eq(1).text(),
        Prop3: $(this).children('td').eq(2).find("select option:selected").val()
    };

        modelArr.push(obj); // Agregar objeto al modelArr 

    });

    $.ajax({
        url: $('form').attr('action'),
        data: {collection: modelArr},
        method: "POST",
        success: function (response){
            console.log(response);
            // Si todo salio bien hacer algo más
        },
        error: function(a){
            console.log(a);
        }
    });

});
    
answered by 13.03.2018 / 20:17
source
0

Make the action of the controller receive as parameter the same type as the Model of the view and it will do the binding well. In that Model class add the List VDTAnalisisHabReqModel as an attribute and put it there.

public ActionResult Specific Competences (TipoDeLaVista collection)

    
answered by 13.03.2018 в 17:29
0

Many thanks to all, I have already been able to do what I was looking for, I leave the code, using JSON and changing the table by a grid I got it.

View:

Script:          

$(function () {
    //$('.edit-mode').hide();
    $('.edit-user, .cancel-user').on('click', function () {
        var tr = $(this).parents('tr:first');
        //tr.find('.edit-mode, .display-mode').toggle();
    });

    $('.save-user').on('click', function () {
        var tr = $(this).parents('tr:first');
        var Item = tr.find("#lblItem").text();
        var Descripcion = tr.find("#lblDescripcion").html();
        var HabilidadId = tr.find("#lblhabilidadId").html();
        var Calificacion = tr.find("#calificacion").val();
        var VdtId = tr.find("#lblvdtId").html();
        tr.find("#lblItem").text(Item);
        tr.find("#lblItem").text(Item);
        tr.find("#lblDescripcion").text(Descripcion);
        // tr.find('.edit-mode, .display-mode').toggle();
        var VDTAnalisisHabReqModel =
            {
                "HabilidadId": HabilidadId,
                "Item": Item,
                "Descripcion": Descripcion,
                "Calificacion": Calificacion,
                "VdtId": VdtId
            };
        $.ajax({
            url: '/VDTCabecera/InsertarDetallesHabilidades/',
            data: JSON.stringify(VDTAnalisisHabReqModel),
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                alert(data);
            }
        });

    });
})

View

    @{
    List<SelectListItem> listItems2 = new List<SelectListItem>();
    listItems2.Add(new SelectListItem
    {
        Text = "4 (Grado Alto)",
        Value = "4",
        Selected = true
    });
    listItems2.Add(new SelectListItem
    {
        Text = "3 (Bueno por encima del estandar)",
        Value = "3"

    });
    listItems2.Add(new SelectListItem
    {
        Text = "2 (Minimo necesario para el puesto)",
        Value = "2"

    });

    listItems2.Add(new SelectListItem
    {
        Text = "1 (Insatisfactorio)",
        Value = "1"

    });
}
@grid.GetHtml(
                                                tableStyle: "webgrid-table",
                                                headerStyle: "webgrid-header",
                                                footerStyle: "webgrid-footer",
                                                alternatingRowStyle: "webgrid-alternating-row",
                                                selectedRowStyle: "webgrid-selected-row",
                                                rowStyle: "webgrid-row-style",
                                                mode: WebGridPagerModes.All,
                                                columns:
                                                    grid.Columns(
                                                     grid.Column("", format: @<text>  <span style="display:none;">@item.HabilidadId </span> <label id="lblhabilidadId" hidden="hidden">@item.HabilidadId</label> </text>, style: "novisible"),
                                                                                                                                   grid.Column("Item", "ITEM", format: @<text>  <span class="display-mode"> <label id="lblItem">@item.Item</label> </span></text>, style: "item"),
                                                                                                                                                                                                          grid.Column("Descripcion", "COMPETENCIA", format: @<text> <span class="display-mode"> <label id="lblDescripcion">@item.Descripcion</label> </span> </text>, style: "competencia"),
                                                                                                                                                                                                   grid.Column("Calificacion", "CALIFICACIÓN", format: @item => Html.DropDownList("calificacion", listItems2, htmlAttributes: new { @class = "form-control" })),
                                                                                                                                                                                                   grid.Column("", format: @<text>  <span style="display:none;">@item.VdtId </span> <label id="lblvdtId" hidden="hidden">@item.VdtId</label> </text>, style: "novisible"),

                                                                                                                                                                                                                                                                                                                          grid.Column("", format: @<text>

                                                                                                                                                                                                                                                                                                                            <button class="save-user display-mode btn btn-primary">Guardar</button>

                                                                                                                                                                                                                                                                                                                        </text>, style: "col3Width", canSort: false)
                                                                                                                                                                                                                                                                                                                                                                                            ))

Controller:

    public JsonResult InsertarDetallesHabilidades(VDTAnalisisHabReqModel model)
    {
        // Update model to your db  
        HabilidadesRequeridasServices habServ = new HabilidadesRequeridasServices();
        string msj = habServ.InsertarDetalleHabilidad(model);
        string message = string.Empty;

        if (msj == "COMPELTO" || msj == "INCOMPLETO")
        {
            message = "El registro fue guardado con exito";
        }
        else
        {
            message = msj;
        }

        if (msj == "COMPLETO")
            ViewBag.Completo = "S";


        return Json(message, JsonRequestBehavior.AllowGet);

    }
    
answered by 13.03.2018 в 22:37