Usuário com melhor resposta
pegar valores de uma table gerada por uma partial view no controller

Pergunta
-
Respostas
-
Não foi resolvido
Junior
- Marcado como Resposta Junior_luiz sexta-feira, 14 de outubro de 2016 17:21
Todas as Respostas
-
Olá Junior, acredito que a forma mais simples de fazer isso seja criar hidden fields na sua tabela com os valores que você precisa percorrer no seu banco de dados, por exemplo:
<html> <tbody> <tr> <td>valor 1</td> <td>valor 2</td> <td>Id do Usuário <input type=hidden value="10" name=IdUsuarios /></td> </tr> </tbody> </table>
No seu controller isso vai chegar em Request.Form["IdUsuarios"]
Consegui ajudar?
-
-
Junior é como eu disse. Você precisa enviar os valores da sua view para o controller. Você não consegue acessar elementos do HTML no seu controller, por isso precisa postar os valores que você quer que cheguem lá.
No exemplo que eu mandei, o que garante isso é o input type=hidden. Se a tabela estiver dentro do seu formulário então os valores dela serão postados para o controller:
<form action="suaAction"> <html> <tbody> <tr> <td>valor 1</td> <td>valor 2</td> <td>Id do Usuário <input type=hidden value="10" name=IdUsuarios /></td> </tr> </tbody> </table> </form>
Desta forma seu controller vai receber um array chamado idUsuarios
public ActionResult ObterDados() { var ids = Request.Form["IdUsuarios"]; //seus tratamentos return View("SuaView"); }
-
Acho que não esta bem claro o que esta querendo fazer
Se a resposta contribuiu com seu aprendizado por favor marque como Útil
Se solucionou seu problema por favor marque como Resposta
Atenção, se seu problema foi resolvido não deixe o post aberto
Visite : www.codigoexpresso.com.br -
vquaiato estou estudando MVC e estou convertendo um site já em produção feito em webforms para MVC 5.
Aqui está minha estrutura assim fica melhor o entendimento
Minhas classes
public partial class PED_PEDIDO { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public PED_PEDIDO() { this.PUS_PEDIDO_USUARIO = new HashSet<PUS_PEDIDO_USUARIO>(); } [Key] public int ped_id { get; set; } [Display(Name="Tipo")] public Nullable<int> ped_tipo { get; set; } [Display(Name="Valor")] public Nullable<decimal> ped_valor { get; set; } public Nullable<decimal> ped_valor_pago { get; set; } public Nullable<decimal> ped_valor_erro { get; set; } [Display(Name="Data Inícial")] [DataType(DataType.Date)] [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)] public Nullable<System.DateTime> ped_periodo_inicial { get; set; } [Display(Name="Data Final")] [DataType(DataType.Date)] [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)] public Nullable<System.DateTime> ped_periodo_final { get; set; } public Nullable<System.DateTime> ped_data_cadastro { get; set; } public Nullable<System.DateTime> ped_data_exclusao { get; set; } public Nullable<System.DateTime> ped_data_confirmado { get; set; } public Nullable<System.DateTime> ped_data_analise { get; set; } public Nullable<System.DateTime> ped_data_processado { get; set; } public Nullable<System.DateTime> ped_data_boleto_impresso { get; set; } public Nullable<System.DateTime> ped_data_habilitado { get; set; } public Nullable<System.DateTime> ped_data_vencimento { get; set; } public Nullable<System.DateTime> ped_data_pagamento { get; set; } [Display(Name="Mês Ref.")] public string ped_referencia { get; set; } public string ped_nosso_numero { get; set; } public string ped_nota_credito { get; set; } public string ped_arquivo_banco { get; set; } public string ped_nsu { get; set; } public Nullable<int> ped_usuario_sigom { get; set; } public Nullable<int> cli_id { get; set; } public Nullable<int> dep_id { get; set; } public Nullable<int> ccu_id { get; set; } public Nullable<int> cat_id { get; set; } public Nullable<int> tpe_id { get; set; } public virtual CAT_CATEGORIA CAT_CATEGORIA { get; set; } public virtual CCU_CENTRO_CUSTO CCU_CENTRO_CUSTO { get; set; } public virtual CLI_CLIENTE CLI_CLIENTE { get; set; } public virtual DEP_DEPARTAMENTO DEP_DEPARTAMENTO { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<PUS_PEDIDO_USUARIO> PUS_PEDIDO_USUARIO { get; set; } } public partial class PUS_PEDIDO_USUARIO { public int pus_id { get; set; } public Nullable<decimal> pus_valor { get; set; } public string pus_erro { get; set; } public Nullable<System.DateTime> pus_data_recarga { get; set; } public Nullable<decimal> pus_valor_recarga { get; set; } public string pus_local_recarga { get; set; } public Nullable<int> ped_id { get; set; } public Nullable<int> usu_id { get; set; } public Nullable<int> tar_id { get; set; } public virtual PED_PEDIDO PED_PEDIDO { get; set; } public virtual TAR_TARIFA TAR_TARIFA { get; set; } public virtual USU_USUARIO USU_USUARIO { get; set; } }
Minha partial view onde mostro os usuários da empresa conectada
@model IEnumerable<MVCEstudante.Models.USU_USUARIO> @section scriptHeader{ <script src="@Url.Content("~/Scripts/jquery.mask.js")" type="text/javascript"></script> } <script> $(document).ready(function () { $(".mask").mask("#.##0,00", { reverse: true }); }); </script> <table id="usupedido" class="table"> <tr> <th></th> <th> @Html.DisplayNameFor(model => model.usu_matricula) </th> <th> @Html.DisplayNameFor(model => model.usu_nome) </th> <th> @Html.DisplayNameFor(model => model.usu_tipo) </th> <th> @Html.DisplayNameFor(model => model.usu_valor_pedido) </th> </tr> @foreach (var item in Model) { <tr> <td> @Html.HiddenFor(modelItem => item.usu_id) </td> <td> @Html.DisplayFor(modelItem => item.usu_matricula) </td> <td> @Html.DisplayFor(modelItem => item.usu_nome) </td> @switch (item.usu_tipo) { case 2: <td> Avulso </td> break; case 3: <td> Estudante </td> break; } <td> @Html.TextBoxFor(m => item.usu_valor_pedido, new { @class = "mask" }) @*@Html.TextboxFor(Model => item.usu_valor_pedido) @Html.DisplayFor(modelItem => item.usu_valor_pedido)*@ </td> </tr> } </table>
Meu controller Pedido
[HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "ped_tipo,ped_valor,ped_periodo_inicial,ped_periodo_final,ped_data_cadastro,ped_referencia,ped_nota_credito,cli_id,cat_id,tpe_id")]PED_PEDIDO pED_PEDIDO, FormCollection frm) { var codempr = Convert.ToInt32(HttpContext.Session["usuarioLogadoID"]); string departamento = frm["dep_id"].ToString(); decimal totalpedido = Convert.ToDecimal(frm["totpedido"]); Int32 pedtipo = Convert.ToInt32(frm["Tipo"]); DateTime perini = Convert.ToDateTime(frm["ped_periodo_inicial"]); DateTime perfim = Convert.ToDateTime(frm["ped_periodo_final"]); DateTime agora = DateTime.Now.Date; string pedref = frm["ped_referencia"]; string notacred = "N"; Int32 categoria = Convert.ToInt32(frm["cat_id"]); Int32 pedtip = 95; try { if (ModelState.IsValid) { //salvando o pedido PED_PEDIDO pedido = new PED_PEDIDO(); pedido.ped_tipo = pedtip; pedido.ped_valor = totalpedido; pedido.ped_periodo_inicial = perini; pedido.ped_periodo_final = perfim; pedido.ped_data_cadastro = agora; pedido.ped_referencia = pedref; pedido.ped_nota_credito = notacred; pedido.cli_id = codempr; pedido.cat_id = categoria; pedido.tpe_id = pedtip; db.PED_PEDIDO.Add(pedido); db.SaveChanges(); //aqui é onde quero percorrer a tabela e gravar os usuarios do pedido } return RedirectToAction("Index"); } catch (Exception ex) { return RedirectToAction("error"); } }
Junior
-
Não foi resolvido
Junior
- Marcado como Resposta Junior_luiz sexta-feira, 14 de outubro de 2016 17:21