How to use @Html.Radiobutton, how to send the selected option to the controller?

Asked

Viewed 10,463 times

2

I’m trying to send the selected option of Radiobutton to the controller, I’ve tried to do several ways, I’ve searched several places and I don’t have a solution. Thanks

Index

@model List<SistemaMobile.Models.cliente>

@{
    ViewBag.Title = "";
}


@using (Html.BeginForm())
{
   <fieldset data-role="controlgroup">

      <input type="radio"  name="@Html.RadioButton("nome", "Nome", true)" id="radio-choice-v-2a"  value="1"  >
      <label for="radio-choice-v-2a">Seu Nome</label>
      <input type="radio"  name="@Html.RadioButton("pai", "Pai", true)" id="radio-choice-v-2b"  value="1"  >
      <label for="radio-choice-v-2b">Nome do Pai</label>
      <input type="radio"  name="@Html.RadioButton("mae", "Mae", true)" id="radio-choice-v-2c"  value="1"  >
      <label for="radio-choice-v-2c">Nome da Mãe</label>
         
   </fieldset> 
    
    <fieldset>
        <label for="search">Localizar:</label>
        <input type="search" name="search1" id="pesquisa" placeholder="buscar registro...">
    </fieldset>

     <input id="enviar" type="submit" value="Localizar"  data-icon="grid" data-iconpos="right"  data-theme="e">
 
}

 <p>@TempData["titulo1"]</p>       

  <ul data-role="listview" data-autodividers="true" data-inset="true" data-theme="e">

      @if (Model.Count() > 0)
      {
         foreach (var item in Model)
          {
            <li><a href="@Url.Action("AtualizaCliente", "ConsultaCliente", new { id = item.idcliente })">@Html.DisplayFor(c => item.nome) </a></li> 
           }
      }
      else
      {
        <label>Você não tem dados cadastrados.</label>
      }
  </ul>

Controller

 [HttpPost]
    public ActionResult Index(string recebeNome, int recebeOpcao)
    {
        try
        {
            sistema_mobileEntities dao = new sistema_mobileEntities();
            IQueryable<cliente> sql;
            sql = null;

            if (recebeOpcao == 1)
            {
                sql = from c in dao.cliente
                      where c.nome.StartsWith(recebeNome.Trim())
                      select c;
                TempData["opcao1"] = "nome";
            }
            return View(sql.ToList());

        }
        catch (Exception ex)
        {
             TempData["Erro"] = "Erro na gravação dos dados " + ex.Message;
        }

        return View();

    }

3 answers

3


If your problem is just sending the selected value to the Controller, just change the part of your RadioButton. I think you just mixed it up HTML with Helpers.

But this part in your View:

<fieldset data-role="controlgroup">

      <input type="radio"  name="@Html.RadioButton("nome", "Nome", true)" id="radio-choice-v-2a"  value="1"  >
      <label for="radio-choice-v-2a">Seu Nome</label>
      <input type="radio"  name="@Html.RadioButton("pai", "Pai", true)" id="radio-choice-v-2b"  value="1"  >
      <label for="radio-choice-v-2b">Nome do Pai</label>
      <input type="radio"  name="@Html.RadioButton("mae", "Mae", true)" id="radio-choice-v-2c"  value="1"  >
      <label for="radio-choice-v-2c">Nome da Mãe</label>

   </fieldset> 

You change to this:

<fieldset data-role="controlgroup">

        <input type="radio" name="recebeOpcao" id="radio-choice-v-2a" value="1">
        <label for="radio-choice-v-2a">Seu Nome</label>
        <input type="radio" name="recebeOpcao" id="radio-choice-v-2b" value="2">
        <label for="radio-choice-v-2b">Nome do Pai</label>
        <input type="radio" name="recebeOpcao" id="radio-choice-v-2c" value="3">
        <label for="radio-choice-v-2c">Nome da Mãe</label>

    </fieldset>

Thus the value selected in each RadioButton with the name="recebeOpcao"will be passing to your Controller and you can work with him.

  • I spent two days trying to figure out the best way to send View parameters to the Controller I tried many solutions I spent hours in the forum, and with your answer I could observe that it is possible to pass any "name" property of an HTML to the controller in a very simple way. What I’m surprised at is that I’m sure a lot of other people knew that and walked past this pole without saying a word. The more I am very grateful to learn this, I’m sure it will be a great differential for me.

  • @itasouza It’s not really a question of not having spoken. It is often difficult to understand what the AP is needing. I understood why I’ve had this same doubt.

1

Dude.

You can use it too, like this:

                    <div class="row">
                        <div class="input-field col s3">
                            <label for="imp_tx_tipo">TIPO:</label>
                        </div>
                    </div>
                    <div class="row">
                        <div class="input-field col s3">
                            <div>


                                <p>
                                    @{string FAX = ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId("FAX");}
                                    @Html.RadioButtonFor(model => model.imp_tx_tipo, "FAX", new { id = FAX, name = "imp_tx_tipo", value = "FAX",@class="with-gap"})
                                    <label for="FAX">FAX</label>
                                </p>
                                <p>
                                    @{string USB = ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId("USB");}
                                    @Html.RadioButtonFor(model => model.imp_tx_tipo, "USB", new { id = USB, name = "imp_tx_tipo", value = "USB", @class = "with-gap" })
                                    <label for="USB">USB</label>
                                </p>
                                <p>
                                    @{string REDE = ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId("REDE");}
                                    @Html.RadioButtonFor(model => model.imp_tx_tipo, "REDE", new { id = REDE, name = "imp_tx_tipo", value = "REDE", @class = "with-gap" })
                                    <label for="REDE">REDE</label>
                                </p>
                                @Html.ValidationMessageFor(model => model.imp_tx_tipo, "", new { @class = "red-text text-darken-2" })

                            </div>
                        </div>
                    </div>

1

Or do for the upgrade:

Controller


//perform search by my type data private void viewbag_imp_tx_type() { List items = new List();

        var db = new projeto_entities();
        var query = db.impressora.Select(c => new { c.imp_tx_tipo }).ToList();
        ViewBag.viewbag_imp_tx_tipo = new SelectList(query.AsEnumerable(), "imp_tx_tipo");

    }

// GET: Printer/Edit/5 public Actionresult editarimpressora(int id_printer) {

        var impressora = impbo.consultar_id_impressora(id_impressora);

        viewbag_local();
        viewbag_imp_tx_tipo();

        return PartialView(impressora);
    }

    // POST: Impressora/Edit/5
    [HttpPost, ActionName("editarimpressora")]
    [ValidateAntiForgeryToken]
    public ActionResult atualizarimpressora([Bind(Include = "locl_nr_id")]int locl_nr_id, impressora imp)
    {

        viewbag_local();
        viewbag_imp_tx_tipo();

        if (ModelState.IsValid)
        {
            try
            {


                if (imp.imp_tx_tipo == "USB" || imp.imp_tx_tipo == "FAX")
                {

                    var _impressora = new impressora()
                    {

                        locl_nr_id          = locl_nr_id,
                        imp_nr_id           = imp.imp_nr_id,
                        imp_tx_marca        = imp.imp_tx_marca.Trim().ToUpper(),
                        imp_tx_modelo       = imp.imp_tx_modelo.Trim().ToUpper(),
                        imp_tx_serie        = imp.imp_tx_serie.Trim().ToUpper(),
                        imp_nm_volts        = imp.imp_nm_volts,
                        imp_nm_ip           = "000.000.000.000",
                        imp_nm_patrimonio   = imp.imp_nm_patrimonio,
                        imp_dt_cadt         = imp.imp_dt_cadt,
                        imp_tx_status       = imp.imp_tx_status.Trim().ToUpper(),
                        imp_tx_obs          = imp.imp_tx_obs.Trim().ToUpper(),
                        imp_tx_tipo         = imp.imp_tx_tipo.Trim().ToUpper(),
                        imp_tx_tipo_ip      = "N".Trim().ToUpper(),
                        imp_nm_mac_wifi     = "00:00:00:00:00:00",
                        imp_nm_mac_ethernet = "00:00:00:00:00:00",
                        imp_tx_mon_biv      = imp.imp_tx_mon_biv.Trim().ToUpper(),
                        imp_tx_tipo_imp     = imp.imp_tx_tipo_imp.Trim().ToUpper()

                    };
                    impbo.atualizar_impressora(_impressora);
                    return RedirectToAction("listarallimpressora");
                }
                else

                    if (imp.imp_tx_tipo == "REDE" && imp.imp_tx_tipo_ip == "D")
                    {
                        var impressora = new impressora()
                        {
                            locl_nr_id          = locl_nr_id,
                            imp_nr_id           = imp.imp_nr_id,
                            imp_tx_marca        = imp.imp_tx_marca.Trim().ToUpper(),
                            imp_tx_modelo       = imp.imp_tx_modelo.Trim().ToUpper(),
                            imp_tx_serie        = imp.imp_tx_serie.Trim().ToUpper(),
                            imp_nm_volts        = imp.imp_nm_volts,
                            imp_nm_ip           = "000.000.000.000",
                            imp_nm_patrimonio   = imp.imp_nm_patrimonio,
                            imp_dt_cadt         = imp.imp_dt_cadt,
                            imp_tx_status       = imp.imp_tx_status.Trim().ToUpper(),
                            imp_tx_obs          = imp.imp_tx_obs.Trim().ToUpper(),
                            imp_tx_tipo         = imp.imp_tx_tipo.Trim().ToUpper(),
                            imp_tx_tipo_ip      = imp.imp_tx_tipo_ip.Trim().ToUpper(),
                            imp_nm_mac_wifi     = imp.imp_nm_mac_wifi,
                            imp_nm_mac_ethernet = imp.imp_nm_mac_ethernet,
                            imp_tx_mon_biv      = imp.imp_tx_mon_biv.Trim().ToUpper(),
                            imp_tx_tipo_imp     = imp.imp_tx_tipo_imp.Trim().ToUpper()
                        };
                        impbo.atualizar_impressora(impressora);
                        return RedirectToAction("listarallimpressora");
                    }
                    else
                        if (imp.imp_tx_tipo == "REDE" && imp.imp_tx_tipo_ip == "E")
                        {
                            var impressora = new impressora()
                            {
                                locl_nr_id          = locl_nr_id,
                                imp_nr_id           = imp.imp_nr_id,
                                imp_tx_marca        = imp.imp_tx_marca.Trim().ToUpper(),
                                imp_tx_modelo       = imp.imp_tx_modelo.Trim().ToUpper(),
                                imp_tx_serie        = imp.imp_tx_serie.Trim().ToUpper(),
                                imp_nm_volts        = imp.imp_nm_volts,
                                imp_nm_ip           = imp.imp_nm_ip,
                                imp_nm_patrimonio   = imp.imp_nm_patrimonio,
                                imp_dt_cadt         = imp.imp_dt_cadt,
                                imp_tx_status       = imp.imp_tx_status.Trim().ToUpper(),
                                imp_tx_obs          = imp.imp_tx_obs.Trim().ToUpper(),
                                imp_tx_tipo         = imp.imp_tx_tipo.Trim().ToUpper(),
                                imp_tx_tipo_ip      = imp.imp_tx_tipo_ip.Trim().ToUpper(),
                                imp_nm_mac_wifi     = imp.imp_nm_mac_wifi,
                                imp_nm_mac_ethernet = imp.imp_nm_mac_ethernet,
                                imp_tx_mon_biv      = imp.imp_tx_mon_biv.Trim().ToUpper(),
                                imp_tx_tipo_imp     = imp.imp_tx_tipo_imp.Trim().ToUpper()

                            };
                            impbo.atualizar_impressora(impressora);
                            return RedirectToAction("listarallimpressora");
                        }

            }
            catch (DataException)
            {
                ModelState.AddModelError("", "Nao Foi Possivel Atualizar o Dado da Impressora. Favor Entrar em Contato com o Administrador...");
            }
        }
        return View();
    }
}

In my view:

TYPE:
                    <div class="row">
                        <div class="input-field col s3">
                            <div>
                                @{
                                // In a real system we would get this list from the database
                                List<SelectListItem> lista = new List<SelectListItem>();
                                lista.Add(new SelectListItem() { Text = "FAX", Value = "FAX" });
                                lista.Add(new SelectListItem() { Text = "USB", Value = "USB" });
                                lista.Add(new SelectListItem() { Text = "REDE", Value = "REDE" });
                                }

                                @{
                                        foreach (var opt in @ViewBag.viewbag_imp_tx_tipo)
                                        {
                                              string FAX = ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId("FAX"); 
                                              string USB = ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId("USB"); 
                                              string REDE = ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId("REDE");

                                        <p>

                                            @Html.RadioButton("imp_tx_tipo", "FAX",  new { id = "FAX",  List = lista, value="FAX"})
                                            @*<input name="imp_tx_tipo" type="radio" id="FAX" class="with-gap" value="FAX" checked />*@
                                            <label for="FAX">FAX</label>
                                            @Html.RadioButton("imp_tx_tipo", "USB", new { id = "USB", List = lista, value = "USB" })
                                            @*<input name="imp_tx_tipo" type="radio" id="USB" class="with-gap" value="USB" />*@
                                            <label for="USB">USB</label>
                                            @Html.RadioButton("imp_tx_tipo", "REDE", new { id = "REDE", List = lista, value = "REDE" })
                                            @*<input name="imp_tx_tipo" type="radio" id="REDE" class="with-gap" value="REDE" />*@
                                            <label for="REDE">REDE</label>

                                        </p>
                                            break;
                                        }

                                @Html.ValidationMessageFor(model => model.imp_tx_tipo, "", new { @class = "red-text text-darken-2" })
                                }
                            </div>
                        </div>
                    </div>

Go our separate ways !!

Good luck!!

Browser other questions tagged

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