0

I'm having problems while submitting the form and saving the filled fields within my database. Actually, this is happening just for one of my fields (model.CampoExtra), which in this case is a multiple select dropdowlist (lPagamentos). I need to save the keys of user selected items in my database, but when the user select more than one item I'm saving just a single key(the first one) and losing the rest of them.

The string containing the selected keys has this format 'key1,key2,keyN, ....'. The column in question that must receive these values has enough size, it was declared as [varchar] (80), so I really do not understand where I'm missing. I'll share sample of the code and hopefully someone can point out a mistake.

Sample of Form code (View)

@{
   

    List<SelectListItem> lPagamentos = new List<SelectListItem>();
    
    DropDownList DDList = new DropDownList();

    lPagamentos = DDList.GetListaCampoExtraFormasPGTO();

}

<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="~/Scripts/select2.min.js"></script>
<link href="~/Content/CSS/select2.css" rel="stylesheet" />

<div id="Form" class="form-container @ViewBag.Acao">
        <div class="page-header">
            <h1>Cadastro de Mensagens</h1>
        </div>
        @using (Html.BeginForm(Acao, "SMS", FormMethod.Post, new { id = "FRMSms" }))
        {
            @Html.AntiForgeryToken()
            <div class="panel panel-primary">
                <div class="panel-heading">
                    <h4>Preencha com as informações do formulário!</h4>
                </div>
                <div class="panel-body">
                    @Html.HiddenFor(model => Model.MensagemID)
                    <input type="text" id="TotalFP" name="TotalFP" value="@ViewBag.TotalFP" />
                    **<!--THIS RETURNS MY DESIRED RECORD<input type="text" id="PgtoID" name="PgtoID" value="@ViewBag.PgtoID" />-->**


                    @if (Area == "MAS")
                    {
                        <div class="form-group col-md-6">
                            @Html.LabelFor(model => model.EmpresaID, htmlAttributes: new { @class = "control-label" }) <!--Cria tag Label-->
                            @Html.ValidationMessageFor(model => model.EmpresaID, "", new { @class = "text-danger" }) <!--Cria tag span-->
                            @Html.DropDownListFor(model => model.EmpresaID, (List<SelectListItem>)lEmpresas, " - SELECIONE - ", new { @class = "form-control" }) <!--Cria tag select-->
                        </div>
                    }
                    else
                    { @Html.HiddenFor(model => model.EmpresaID)}

                    <div class="form-group col-md-6 CampoForm">
                        @Html.LabelFor(model => model.Tipo, htmlAttributes: new { @class = "control-label" })
                        @Html.ValidationMessageFor(model => model.Tipo, "", new { @class = "text-danger" })
                        @Html.EditorFor(model => model.Tipo, new { htmlAttributes = new { @class = "form-control", placeholder = "Tipo" } })
                    </div>

                    <div class="form-group col-md-12 CampoForm">
                        <label for="Descricao" class="control-label">Descrição <span id="caracteres">120</span> caracteres restantes.</label>
                        @Html.EditorFor(model => model.Descricao, new { htmlAttributes = new { @class = "form-control", maxlength = 120 } })
                    </div>

                    <div class="form-group col-md-12 CampoForm">
                        <label for="Texto" class="control-label">Mensagem <span id="rchars">155</span> caracteres restantes.</label>
                        @Html.ValidationMessageFor(model => model.Texto, "", new { @class = "text-danger" })
                        @Html.TextAreaFor(model => model.Texto, new { @class = "form-control", maxlength = 155 })
                    </div>

                    <div class="form-group col-md-9 CampoForm">
                        <label for="PgtoIDD" class="control-label">Formas de Pagamento - <input type="checkbox" id="chkTodos" /> Selecionar todos</label>
                        <input type="hidden" id="PgtoID" name="PgtoID" />
                        @Html.DropDownListFor(model => model.CampoExtra, (List<SelectListItem>)lPagamentos, new { @class = "form-control mySelect2", name = "CampoExtra", multiple = "multiple", style = "width:100%;" })
                    </div>

                    <div class="form-group col-md-3 CampoForm">
                        @Html.LabelFor(model => model.Situacao, htmlAttributes: new { @class = "control-label" })
                        @Html.ValidationMessageFor(model => model.Situacao, "", new { @class = "text-danger", maxlength = 1 })
                        @Html.DropDownListFor(model => model.Situacao, (List<SelectListItem>)lSituacao, " - SELECIONE - ", new { @class = "form-control" })
                    </div>
                    <div class="form-group col-md-3 CampoForm">
                        <label class="form-label">Cadastro</label>
                        <input id="Cadastro" name="Cadastro" tabindex="-1" type="text" readonly class="form-control" value="@Cadastro" />
                    </div>

                </div>
                <div class="panel-footer">
                    <input type="submit" value="@ViewBag.Label" class="btn btn-primary"> | @Html.ActionLink("Cancelar", "../Sms/", new { id = "", acao = "" }, new { @class = "btn btn-primary" })
                </div>
            </div>
        }
    </div>

<script>    

    $("#Form #CampoExtra").select2({
        placeholder: "Selecione uma(s) forma(s) de pagamento.",
        allowClear: true,
        theme: "classic",
    });

    $("#chkTodos").on("click", function () {
        if (this.checked) {
            $("#Form #CampoExtra").select2('destroy').find('option').prop('selected', 'selected').end().select2();
            var CsID = $("#Form #CampoExtra").val();
            $("#Form #TotalFP").val("S");
            $("#PgtoID").val(CsID);
        } else {
            $("#Form #CampoExtra").select2('destroy').find('option').prop('selected', false).end().select2();
            $("#PgtoID").val('');
            $("#Form #TotalFP").val("");
        }
    })

    $("#Form #CampoExtra").on("change", function () {
        var PgtoID = $(this).val();
        $("#PgtoID").val(PgtoID);

        var isChange = ($("#Form #CampoExtra option:checked").length == $("#Form #CampoExtra option").length);
        $("#chkTodos")[0].checked = isChange;
        var TotalFP = (isChange) ? "S" : "";
        $("#Form #TotalFP").val(TotalFP);
    });

    if ('@ViewBag.PgtoID'.length > 0) {
        $("#Form #CampoExtra").val([@ViewBag.PgtoID]);
        $('#Form #CampoExtra').trigger('change');
    };

</script>

Controller

public ActionResult CadastrarSMS(Sms_Mensagens SmsMensagem)
        {
            bool IsLogado = (Session["IsLogado"] is null);
            if (IsLogado)
            {
                return RedirectToAction("Login", "User", new { acao = "ErroSessao" });
            };
            if (!ModelState.IsValid)
            {
                return View("FormSms", SmsMensagem);
            }

            int MensagemID = SmsMensagem.MensagemID;

            if (MensagemID == 0)
            {
                DBCtx.MensagensDB.Add(SmsMensagem);
            }
            else
            {
                DBCtx.Entry(SmsMensagem).State = EntityState.Modified;
            }

            DBCtx.SaveChanges();

            ViewModelSucesso ViewMS = new ViewModelSucesso();
            ViewMS.Controller = "SMS";
            ViewMS.View = "Index";
            return View("Sucesso", ViewMS);

        }

        public ActionResult FormSMS(int id = 0, string acao = "")
        {

            bool IsLogado = (Session["IsLogado"] is null);
            if (IsLogado)
            {
                return RedirectToAction("Login", "User", new { acao = "ErroSessao" });
            };
            ViewBag.Id = id;
            ViewBag.Acao = acao;

            ViewBag.Label = "Cadastrar";
            if (acao == "Editar") { ViewBag.Label = "Atualizar"; };
            if (id == 0)
            {
                ViewBag.EmID = 0;
                ViewBag.FiID = 0;
                return View();
            }

            Sms_Mensagens SmsMensagem = DBCtx.MensagensDB.Find(id);
            ViewBag.EmID = SmsMensagem.EmpresaID;

            if (SmsMensagem == null)
            {
                return View();
            }
            return View(SmsMensagem);
        } 

Model

public class Sms_Mensagens
    {

        [Key]
        [Display(Name = "ID Mensagem")]
        public int MensagemID { get; set; }

        [Display(Name = "Empresa")]
        public int EmpresaID { get; set; }

        public string Tipo { get; set; }

        [Required(ErrorMessage = " - Preencha a descrição da mensagem!")]
        [Display(Name = "Descrição (até 120 caracteres)")]
        public string Descricao { get; set; }

        [Required(ErrorMessage = " - Descreva o texto da mensagem")]
        [MaxLength(155, ErrorMessage = " - O texto deve conter até {1} caracteres.")]
        [Display(Name = "Mensagem (até 155 caracteres)")]
        public string Texto { get; set; }

        [Required(ErrorMessage = " - Selecione uma ou mais areas!")]
        [Display(Name = "Areas")]
        public string CampoExtra { get; set; }

        [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy HH:mm:ss}", ApplyFormatInEditMode = true)]
        public DateTime Cadastro { get; set; }

        [Required(ErrorMessage = " - Selecione a Situação")]
        [Display(Name = "Situação")]

        public string Situacao { get; set; }
        public virtual Empresas Empresas { get; set; }

    }

public List<SelectListItem> GetListaCampoExtraFormasPGTO()
        {
            List<SelectListItem> Lista = new List<SelectListItem>();
            var data = new[]{
                new SelectListItem{Value = "CC", Text = "CARTÃO DE CRÉDITO" },
                new SelectListItem{Value = "BB", Text = "BOLETOS" },
                new SelectListItem{Value = "DC", Text = "DÉBITO EM CONTA" },
                new SelectListItem{Value = "TE", Text = "TRANSFERÊNCIA ELETRÔNICA" },
                new SelectListItem{Value = "CE", Text = "CONTA DE ENERGIA" },
                new SelectListItem{Value = "CT", Text = "CONTA DE TELEFONE" }
            };
            Lista = data.ToList();
            return Lista;
        }
1
  • You have to make the CampoExtra field to string[] from string as suggested by Roman. You can also use MultiSelectList as described here mikesdotnetting.com/article/265/… Commented Feb 18, 2020 at 14:17

1 Answer 1

2

When your form is submitted, selected options from your CampoExtra dropdown are sent one by one. So the body of your request will contain something like this:

CampoExtra=key1&CampoExtra=key2&CampoExtra=key3

Your Sms_Mensagens.CampoExtra has a string type so it accepts a single string. Try to change this property to have IEnumerable<string> or string[] type. Of course, you'll have to join your selected options manually(string.Join(",", SmsMensagem.CampoExtra)) in order to save it as a single value in the DB.

Note that it might not be a good idea to store comma-separated values in one column(at least in the relational database), maybe it's better to propper normalize your tables.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.