Make Ubmit from a form via ajax

Asked

Viewed 1,338 times

1

I have following code in my controller:

[HttpGet]
    public ActionResult Mensagem(long idT, long idD)
    {
        string raaluno = acr.getAlunoLogado().ToString();
        ViewBag.idT = idT.ToString();
        ViewBag.idD = idD.ToString();
        ViewBag.idL = raaluno;
        return View();
    }

    [ValidateInput(false)]
    [HttpPost]
    public ActionResult Mensagem(DMensagensMetadado mensagens)
    {
        if (ModelState.IsValid)
        {
            String idFT = mensagens.idtopico.ToString();
            String idAL = mensagens.idlogin.ToString();
            String idDD = mensagens.iddisc.ToString();
            String mensagem = mensagens.fptg_mensagem.ToString();
            string retorno = mensagemAplicacao.SalvaMensagem(idFT, idAL, mensagem).ToString();
            if(retorno == "true") {
                return RedirectToAction("Topicos", "EDisciplinas", new { idT = idFT, idD = idDD });
            }
            else
            {
                ViewBag.error_MSG = "false";
                return RedirectToAction("Topicos", "EDisciplinas", new { idT = idFT, idD = idDD });
            }
        }
        return View(mensagens);
    }

and in my partial view of the application I have following code:

@model EADWeb.Areas.EAD.Models.DMensagensMetadado
@{
    Layout = null;
}

@using (Html.BeginForm("Mensagem", "EDisciplinas", FormMethod.Post, new { @class = "ui large fluid form" })) 
{
@Html.AntiForgeryToken()

<div class="ui grid">
    <div class="fourteen wide column centered">
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.TextAreaFor(model => model.fptg_mensagem, new { @class = "ckeditor" })
        @Html.ValidationMessageFor(model => model.fptg_mensagem, "", new { @class = "text-danger" })
        <div class="ui grid">
            <div class="thirteen wide column"></div>
            <div class="three wide column btnMensagem">
                <input id="idtopico" name="idtopico" type="hidden" value="@ViewBag.idT" />
                <input id="idlogin" name="idlogin" type="hidden" value="@ViewBag.idL" />
                <input id="iddisc" name="iddisc" type="hidden" value="@ViewBag.idD" />
                <input type="submit" value="Enviar Mensagem" class="ui fluid large blue submit button" />
            </div>
        </div>
    </div>
</div>
if (@ViewBag.error_MSG != null)
{
    <div class="ui blue basic label">
        @ViewBag.msg_Error
    </div>
}
}

I need to give Submit in the form via ajax to display an error or success message on the screen.

Someone can help me?

Update 1: I found this post on the MSDN forum https://social.msdn.microsoft.com/Forums/pt-BR/fdaac25a-c5c5-47fe-a2c3-26d11c1b3dbf/login-aspnet-mvc-ajax?forum=mvcpt, but I didn’t understand how to implement it in my case.

Update 2:

I made some changes to my controller and layout and have the following encoding:

Controller

[HttpGet]
    public ActionResult Topicos(long idT, long idD)
    {
        ViewBag.IDDisciplina = idD;
        string raaluno = acr.getAlunoLogado().ToString();
        ViewBag.idT = idT.ToString();
        ViewBag.idD = idD.ToString();
        ViewBag.idL = raaluno;
        if (msgOK != "sim")
        { this.ShowMessageError("Mensagem não enviada com sucesso, entre em contato com o suporte!"); }
        else
        { this.ShowMessageInfo("Mensagem enviada com sucesso!"); }
        return View();
    }

    [ValidateInput(false)]
    [HttpPost]
    public JsonResult SalvarMensagem(string idtopico, string idlogin, string iddisc, String mensagemf)

    {
        if (mensagemf == "") { return Json(new { Success = false }, JsonRequestBehavior.AllowGet); }
        else
        {
            String idFT = idtopico;
            String idAL = idlogin;
            String idDD = iddisc;
            String mensagem = mensagemf;
            string retorno = mensagemAplicacao.SalvaMensagem(idFT, idAL, mensagem).ToString();
            if (retorno == "true")
            {
                ViewBag.idT = idFT.ToString();
                ViewBag.idD = idDD.ToString();
                msgOK = "sim";
                return Json(new { Success = true }, JsonRequestBehavior.AllowGet);
            }
            else
            {
                msgOK = "nao";
                return Json(new { Success = false }, JsonRequestBehavior.AllowGet);
            }
        }
    }

_Layout

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/bundles/semanticjs")
@Scripts.Render("~/bundles/ckeditor")
<script [email protected]("~/Scripts/ckeditor/adapters/jquery.js")></script>
<div class="ui inverted top attached blue menu">
    <a class="item">
        <i class="sidebar icon"></i>
        Menu Principal
    </a>
</div>
<div class="ui grid">
    <div class="sixteen wide column">
        <div class="ui left demo vertical inverted labeled sidebar blue menu">
            <div class="ui container">
                <h3 class="item">Menu Principal</h3>
            </div>
            <div class="ui container firstmenu">
                <a id="itemsMD" class="item dalink menus" href="~/EAD/EDisciplinas/Conteudo">Material Didático</a>
                <!--<a id="items" class="item" title="curso" href="#curso">Notas</a>-->
            </div>
            <div class="ui container secondmenu">
                <a id="itemsP" class="item dalink" href="~/EAD/EPrincipal">Disciplinas</a>
                <a id="itemsS" class="item dalink" href="~/EAD/EAccount/Sair">Sair</a>
            </div>
        </div>                    
    </div>
</div>
<div class="ui grid">
    <div class="sixteen wide column specialDP">
        @RenderBody()
    </div>
</div>
<script src="@Url.Content("~/Scripts/Disciplinas.EAD.js")"></script>
@RenderSection("scripts", required: false)

Topics.cshtml

@Html.Action("TopicoFixo", "EDisciplinas")

@Html.Action("TopicoMensagens", "EDisciplinas")


    <div class="respostaSS"></div>
    <div class="ui grid resp">
        <div class="sixteen wide column">
            <form id="form-mensagem" name="form-mensagem" method="post" class="ui large fluid form" action="#">
                <div class="ui grid">
                    <div class="fourteen wide column centered">
                        <textarea id="mensagemf" name="mensagemf" class="ckeditor"></textarea>
                        <div class="ui grid">
                            <div class="twelve wide column"></div>
                            <div class="four wide column btnMensagem">
                                <input id="idtopico" name="idtopico" type="hidden" value="@ViewBag.idT" />
                                <input id="idlogin" name="idlogin" type="hidden" value="@ViewBag.idL" />
                                <input id="iddisc" name="iddisc" type="hidden" value="@ViewBag.idD" />    
                                <a id="botao-entrar" class="ui fluid large blue submit button" ><i class="send icon"></i> Enviar Mensagem</a>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <div class="rodape"></div>

    <script type="text/javascript">
        $(function () {

            $('<a>', {
                class: 'item dalink',
                href: '/EAD/EDisciplinas/Index/@ViewBag.IDDisciplina',
                text: 'Avisos'
            }).appendTo('.firstmenu:last');

            $('<a>', {
                class: 'item dalink',
                href: '/EAD/EDisciplinas/Forum/@ViewBag.IDDisciplina',
                text: 'Forum de Discussão'
            }).appendTo('.firstmenu:last');


        });
    </script>

Disciplines.EAD.js

$(function () {
$('.left.demo.sidebar').first()
    .sidebar('attach events', '.attached.menu');
$('.grid.resp').hide();
$('#dialog').click(function () {
    $('.grid.resp').show('normal');
    var hasFocus = $('.respostaSS').is(':focus');
});

$('#botao-entrar').click(function () {
    var data = {
        "idtopico": $("#idtopico").val(),
        "idlogin": $("#idlogin").val(),
        "iddisc": $("#iddisc").val(),
        "mensagemf": $("#mensagemf").val()
    }
    var idT, idD;
    idT = $("#idtopico").val();
    idD = $("#iddisc").val();
    var mensagem = $("#mensagemf").val();
    if (mensagem != "") {

        $.ajax({
            url: "/EDisciplinas/SalvarMensagem",
            type: "POST",
            data: JSON.stringify(data),
            dataType: "json",
            contentType: "application/json",
            success: function (response) {
                if (response.Success) {
                    $.get('@Url.Action("Topicos", "EDisciplinas", new { idT = ' + idT + ', idD = ' + idD + ' })', function (data) {
                        $('.container').html(data);
                    });
                }
                else {
                    $.get('@Url.Action("Topicos", "EDisciplinas", new { idT = ' + idT + ', idD = ' + idD + ' })', function (data) {
                        $('.resp').html(data);
                    });
                }
            },
            error: function () {
                console.log('Login Fail!!!');
            }
        })
    }
});
});

Help me because when I click the login button it doesn’t call the function.

Update 3

I changed everything and made the following code in the controller:

[HttpGet]
    public ActionResult Topicos(long idT, long idD)
    {
        ViewBag.IDDisciplina = idD;
        string raaluno = acr.getAlunoLogado().ToString();
        ViewBag.idT = idT.ToString();
        ViewBag.idD = idD.ToString();
        ViewBag.idL = raaluno;
        return View();
    }

    [ValidateInput(false)]
    [HttpPost]
    public Action SalvaMSG(DMensagensMetadado mensagem)
    {
        if (ModelState.IsValid)
        {
            retorno = mensagemAplicacao.SalvaMensagem(mensagem.idtopico, mensagem.idlogin, mensagem.fptg_mensagem).ToString();
            if (retorno == "True")
            {
                resultado = "True";
            }
            else
            {
                resultado = "False";
            }
        }
        Response.Write(resultado);
        return null;
    }

And in the view comes the code:

<div class="ui grid respostaSS" id="respostaSS"></div>

<div class="ui grid resp">
    <div class="sixteen wide column">
        <form id="formM" name="formM" method="post">
            <div class="ui grid">
                <div class="fourteen wide column centered">
                    <textarea id="fptg_mensagem" name="fptg_mensagem" class="ckeditor"></textarea>
                    <div class="ui grid">
                        <div class="twelve wide column"></div>
                        <div class="four wide column btnMensagem">
                            <input id="idtopico" name="idtopico" type="hidden" value="@ViewBag.idT" />
                            <input id="idlogin" name="idlogin" type="hidden" value="@ViewBag.idL" />
                            <input id="iddisc" name="iddisc" type="hidden" value="@ViewBag.idD" />
                            <button type="submit" id="botao-entrar" onclick="CKupdate()" class="ui fluid large blue submit button"><i class="send icon"></i> Enviar Mensagem</button>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>

<div class="rodape"></div>
    <script type="text/javascript">
    $(function () {

        $('<a>', {
            class: 'item dalink',
            href: '/EAD/EDisciplinas/Index/@ViewBag.IDDisciplina',
            text: 'Avisos'
        }).appendTo('.firstmenu:last');

        $('<a>', {
            class: 'item dalink',
            href: '/EAD/EDisciplinas/Forum/@ViewBag.IDDisciplina',
            text: 'Forum de Discussão'
        }).appendTo('.firstmenu:last');

        $("form").submit(function () {
        $.post('SalvaMSG', $('form').serialize()).success(function (response) {
            if(response != "False"){
                toastr.success('Mensagem Enviada');
            }
            else{
                toastr.error('Mensagem não enviada!', 'Entre em contato com o suporte.');
            }

            setTimeout(function(){
                window.location.href = '/EAD/EDisciplinas/Topicos?idT=' + @ViewBag.idT + '&idD=' + @ViewBag.idD;
            }, 10000);
            });
        });
    });

    function CKupdate() {
        for (instance in CKEDITOR.instances)
            CKEDITOR.instances[instance].updateElement();
        $('textarea').trigger('keyup');
    }
</script>
  • @Randrade can help me?

  • @Gypsy Rhyrrisonmendez can help me?

  • What is the purpose of being in Ajax? Have you tried using the Ajax.Beginform()? Any error appears in console (F12)? Sorry it doesn’t help now, but I’m on the phone, I can’t come up with an answer now, but tomorrow morning I do a.

2 answers

2

For starters, you can’t mix code C# with JavaScript the way you want to do it here:

if (response.Success) {
    $.get('@Url.Action("Topicos", "EDisciplinas", new { idT = ' + idT + ', idD = ' + idD + ' })', function (data) {
        $('.container').html(data);
    });
}
else {
    $.get('@Url.Action("Topicos", "EDisciplinas", new { idT = ' + idT + ', idD = ' + idD + ' })', function (data) {
        $('.resp').html(data);
    });
}

There are two ways to do this:

first: Doing the same is doing in the Ajax, but concatenating the Javascript:

  $.get('/EDisciplinas/Topicos?idT=' + idT + '&idD=' + idD, function (data) {
            $('.container').html(data);
        });

2nd: Contact the code correctly (I advise this):

 $.get('@Url.Action("Topicos", "EDisciplinas")?idT=' + idT + '&idD=' + idD, function (data) {
          $('.resp').html(data);
  });

Once done, your code will work.

There are many errors in your code, such as forms of validations, how are returning values to the screen, misuse of Actions, among other things. I will not comment on this because otherwise I will leave the subject.

  • On second thought I see here that you are correct, but how would I use ajax.beginform? and what I would have to change in my action?

  • @Deividfarias After seeing your code I think it would not be the best option for you. With the Ajax.BeginForm() you will work with events and functions, which would end up complicating more what you are doing.

  • So how could I perform the procedure?

  • @Deividfarias I did not understand. With the is in the answer still does not work?

  • It doesn’t really call the function. I’m almost redoing everything (like erase everything and start again)

  • @Deividfarias Here worked normally. I put it in my Github for you to see. Remembering that it will only be sent when you have some message on textbox.

  • Remembering that I don’t know what you want to do. The return of the function leaves the background black here. But it goes to the controller and returns.

  • if I explain to you what I want you can help me?

Show 4 more comments

0


After help from some community members I came to the following solution to my problem:

HTML

<div class="content">
<form id="formT" name="formT" method="post" class="ui fluid form">
    <div class="field">
        <div class="ui left icon input">
            @Html.TextAreaFor(model => model.ftpc_descricao, new { placeholder = "Descrição" })
            <div class="ui blue basic label" id="descricao">
                <span class="validaTD"></span>
            </div>
        </div>
    </div>
    <div class="field">
        <div class="ui left icon input">
            <div class="ui checkbox">
                <input type="checkbox" name="ftpc_st_id" id="ftpc_st_id">
                <label>Ativo?</label>
            </div>
            <div class="ui blue basic label" id="status">
                <span class="validaTS"></span>
            </div>
        </div>
    </div>
    <div class="field">
        <div class="ui left icon input">
            @Html.Action("ITDisciplinas", "IForum")
            <div class="ui blue basic label" id="disciplinas">
                <span class="validaTDD"></span>
            </div>
        </div>
    </div>
    <div class="actions">
        <a id="btnSave" class="ui positive ok right labeled icon button">
            Salvar
            <i class="save icon"></i>
        </a>
    </div>
</form>

JS (Jquery)

$('#btnSave').click(function () {
            if (validaCampos()) {
                var descricao = $('#ftpc_descricao').val();
                var status;
                if ($('#ftpc_st_id').is(':checked')) { status = 1; } else { status = 2; }
                var disciplina = selecionado;
                var Dados = {
                    ftpc_descricao: $('#ftpc_descricao').val(),
                    ftpc_st_id: status,
                    ftpc_dp_id: selecionado
                };

                $.ajax({
                    type: "POST",
                    url: "/IForum/ICreateTopicos",
                    data: JSON.stringify(Dados),
                    contentType: 'application/json; charset=utf-8',
                    success: function (data) {
                        if (data.msg == "Salvo") {
                            toastr.success("Tópico salvo com sucesso!", "Mensagem do Sistema");
                            window.setTimeout('location.reload()', 5000);
                        }
                        else {
                            toastr.error("Tópico não salvo. Entre em contato com o suporte", "Mensagem do Sistema");
                            window.setTimeout('location.reload()', 5000);
                        }
                    }
                });
            }
        });

Controller

public ActionResult ICreateTopicos(IForumIntraMetadado top)
    {
        bool resultado = forumAplicacao.SalvarTopico(top.ftpc_descricao, top.ftpc_dp_id.ToString(), top.ftpc_st_id.ToString());
        if (resultado)
        {
            return Json(new { msg = "Salvo" });
        }
        else
        {
            return Json(new { msg = "NSalvo" });
        }
    }

I use the toastr to send messages on the page.

Thanks to @Randrade and @Bacco for their help in getting my answer.

Browser other questions tagged

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