Make submit a form via ajax

1

I have the 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);
    }

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 screen.

Can anyone help me?

Update 1: I found this post in the MSDN forum link , but I did not understand how to implement it in my case.

Update 2:

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

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)

Topicos.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 enter button it does not 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>
    
asked by anonymous 08.06.2016 / 03:54

2 answers

0

After some help from some community members, I came up with 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 toastr to send messages on the page.

Thanks for the help of @Randrade and @Bacco, for the help to get my answer.

    
16.06.2016 / 00:18
2

To begin with, you can not mix code C# with JavaScript the way you want to do 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:

1st: Doing same is done in Ajax , but concatenating Javascript :

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

2nd: Please enter the code correctly (I advise you):

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

Once you've done this, your code will work.

  

There are many errors in your code, such as validation forms, how to return values to the screen, misuse of Actions , and so on. I will not comment on this, otherwise I will get away from it.

    
09.06.2016 / 15:07