Take the value of a form that has a list

Asked

Viewed 1,576 times

1

You guys all right? it’s me again, I know I’m asking a lot of questions, but I’m having a few questions and I can’t find an answer, I’m wanting to capture the event of a button in Asp.net mvc using Razor, I’m with the following button:

<input type="button" value="Salvar" onclick="location.href='@Url.Action("insert")'" />

and this is my code from controller

    public ActionResult insert()
    {
        myMetodInsert();//futuro método que ira inserir dados na base
        return List();
    }

The method returns another method List that returns a view, but I noticed that he tries to access a page with the name of the method, but this is not the intention. The intention is to call a method that will include data in the database and then return the page. They could help?


Edit

The question is this: I open a page with a list of goods, where the person can change only the value of the merchandise. This list contains in its first element a selection field with checkbox (worthwhile boolean in the same).

As soon as the person marks the checkbox, it enables editing. At the moment the person clicks the button salvage, i must capture this event, receive this modified list and persist the change in the database.

I am in doubt only in capturing the event. When I used java with JSF, just put the bean + method on the button he identified it. On Asp.net MVC there is nothing like it?

For further clarification follow the code like this:

View

@model Teste.Models.Produto

@{
    Layout = null;
}
@using (Html.BeginForm("Salvar", "ListaProdutoCab", FormMethod.Post))
{
    <table>
        <thead>
            <tr>
                <th>Selecione</th>
                <th>Produto</th>
                <th>Valor</th>

            </tr>
        </thead> @foreach (var item in Model.listaBebida)
        {
            <tr>
                <td> @Html.CheckBoxFor(modelItem => item.isEditado)</td>
                <td> @Html.TextBoxFor(modelItem => item.produto, new { disabled = "disabled" }) </td>
                <td> @Html.TextBoxFor(modelItem => item.valor) </td>

            </tr>
        }
    </table>
    <div id="modal">
        <div id="botoes">
            <button type="submit">Salvar</button>
        </div>
    </div>
}

My Controller:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Teste.DAO;
using Teste.Models;

namespace Teste.Controllers
{
    public class ListaProdutoCab: Controller
    {
        //
        // GET: /ListaProdutoCab/
        ListaProdutoService service = new ListaProdutoService();
        Produto produto = new Produto();
        Session usuario = new Session("Genisson", 058);

        List<ObjectMasterProduto> listaProduto= new List<ObjectMasterProduto>();

        public ActionResult ListaProdutoCab()
        {
            return View();
        }

        public ActionResult List()

        {
            service.carregarListaBebida(produto.listaBebida);
            return PartialView(produto);
        }
        [HttpPost]
        public ActionResult Salvar()
        {
            service.Salvar(produto.listaBebida, usuario);
            return RedirectToAction("List");
        }

    }
}

Product

 public class Produto
    {

        //Chamadas externas
        public Bebida bebida{ get; set; }

        public List<Bebida> listaBebida{ get; set; }

        public Produto()
        {

        }


    }

Drinking class

public class bebida
    {

        //Chamadas externas
        public String nome{ get; set; }

        public Double Valor{ get; set; }

        public Bebida()
        {

        }


    }

From to do what I need only using the native Asp.net mvc? api or will I need to actually use other api’s?

  • Wouldn’t it be better to use Ajax to do what you want?

  • I agree with @Ciganomorrisonmendez , use AJAX.

  • Change the question and place the class structure Produto that I make another answer more appropriate to answer your question.

  • Question now this modified with the product and drink class

2 answers

1

If you will use a form to enter data, you must put the type of button as submit.

If that’s the case, try doing something like this:

@using(Html.BeginForm("Salvar", "Algum", FormMethod.Post))
{
    <input type="text" name="nome" />
    <button type="submit">Salvar</button>
}

And in the controller do something like this:

public class AlgumController : Controller
{
    public ActionResult Salvar(string nome)
    {
        Respositorio.Salvar(nome);
        return RedirectToAction("Listar");
    }

    public ActionResult Listar()
    {
        var lista = Repositorio.Listar();

        return View("Lista", lista);
    }
}

Doing this the method Salvar will receive the name value corresponding to the input HTML and will call a method to perform the save action. After saving the method returns a RedirectToAction which will redirect to the method Listar.

Editing:

If you are using jQuery in your project you can do the following:

$('#meu-btn').on('click', function()
{
    var dadosParaSalvar = coletarDadosDaTabela();

    $.ajax({
        cache: false,
        type: "GET",
        url: 'Algum/Salvar', //'Controller/Action'
        data: { dados: dadosParaSalvar },
        success: function (response) {
            if (response.error == undefined || response.success) {
                try {
                    //Válido apenas se você retornar a lista como JSON, utilizando JsonResult,
                    //caso contrário deve-se utilizar o JSON.parse('string')
                    var lista = response;

                    consumirListaDeRetorno(lista);
                }
                catch (err) {
                    Erro(err);
                }
            }
        }
    });
});

And in the controller to receive the data sent by ajax and return a JSON do as follows:

public class AlgumController : Controller
{
    //Todos os registros que forem passados para uma action, desde que possuam o tipo correto
    //e o mesmo nome são encapsulados automáticamente em uma classe modelo, como a classe 'ClasseModelo'.
    //Se todos os dados possuirem corretamente as propriedades presentes na classe 'ClasseModelo', o array passado
    //utilizando ajax será automáticamente convertido para uma List<ClasseModelo>.
    public ActionResult Salvar(IList<ClasseModelo> dados)
    {
        //Aqui você adiciona a lógica para o salvamento das informações
        Respositorio.Salvar(dados);
        //Aqui você gera uma lista atualizada dos dados que deseja retornar
        var listaAtualizada = Repositorio.Listar();

        //Aqui você passa o objeto 'listaAtualizada' como primeiro parâmetro para que
        //ele seja serializado no formano JSON para o retorno.
        //O segundo parâmetro permite que o retorno JSON seja permitido utilizando o método HTTP GET
        return Json(listaAtualizada , JsonRequestBehavior.AllowGet);
    }
}

So you will collect the data using JavaScript, will send to your controller using the Ajax, process the data in the controller and return a JSON so that the callback success of ajax use the return list.

  • I think what he wants is to call a JS and get the list by a JsonResult.

  • I’m not sure about that, so I suggested this option. He says he wants to return a page. If this is the case and it makes clear this intention I modify the answer incrementing with the option for a JSON return.

  • He edited the question. I think that’s right.

  • Is there any way to get the session object (in this case the list) in my controller without having to use Jquery or ajax? I’ve been trying to get the list that is logged in, but when calling the controller it runs all variables, so I can’t get my list already loaded and with the modified fields that are in my view, if it is not possible I will be using the proposed solution.

  • I’m not sure I understand the question, but when changing in the view (using a browser for example) the data is not modified in the session, at least not without using javascript. If you just want to change the list values in the session and then return the list that is in the session, this can be done.

  • then my doubt is totally this, I want to save the changes of that list that I loaded in the controller, because the field 'value' is enabled for such a feat, so when for example, bring the product coca-cola with the value of 4,75, the user can change for example in this list the value to 5,00, if he clicks save, my save action should take this list that is in the session and pass it as parameter for my 'save' method of my service, I do not know if it got a little confused but this is it. if you have how to show me some tutorial or how to?

  • I understood, but I think you are seeing the functioning of ASP.NET MVC incorrectly. When you return your list to a view and it is displayed to the user it is not stored in session. And the changes the user makes are not reflected in your controller list. These changes made by the user are sent to the controller using the HTTP methods. So the right thing is for you to use a <form> or ajax. MVC allows you to use an "ajax form" to do what you want without reloading the page.

  • I am already using the form, according to the code I posted above, I would just like to know how to receive this list that I am displaying in the form, and how to receive it as a parameter in my actionResult save

Show 3 more comments

0

People after some time searching, I found that the foreach is not very recommended in this case, because it duplicates the id’s and leaves invalid at the level of html. disable property makes the values return form null, the solution was to change from foreach to for and exchange disable for readonly, thanks staff.

Browser other questions tagged

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