How to use the @Html.RadioButton, how to send the select option to the controller?

2

I'm trying to send the selected RadioButton option to the controller, I've already tried to do it in several ways, I've researched in several places and I do not have a solution. Thank you

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();

    }
    
asked by anonymous 07.04.2015 / 20:34

3 answers

3

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

But in 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>

So the value selected in each RadioButton with name="recebeOpcao" will be passed to your Controller and you can work with it.

    
07.04.2015 / 21:11
1

Dude.

You can use this as well:

                    <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>
    
24.01.2017 / 16:16
1

Or do the upgrade:

Controller

// search for my data of type         private void viewbag_imp_tx_tipo ()         {             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 editimpressora (int print_id)         {

        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 the way of each one !!

Good luck !!

    
25.01.2017 / 15:11