简体   繁体   中英

Ajax refreshing page in MVC

I'm using Ajax to pass some data to a Controller and save to database, and it works, the issue that is refreshing the page with every POST and I need to prevent that.

Ajax:

function AddComment(commet, auto) {
    $.ajax({
        type: "POST",
        url: '/bff/SaveComment',
        data: { id: idParte, commenta: commet, autoriza: auto },
        dataType: 'json',
        success: function (correct) {
            $("#win1").show().kendoWindow({
                width: "300px",
                height: "100px",
                modal: true,
                title: "Added"
            });
        },
        errror: function(inc) {
        }
    });
}

Controller:

[HttpPost]
public JsonResult SaveComment(int id, string commenta, string autoriza)
{
    // Some logic here
    return Json("");
}

Tried this way with correct.preventDefault(); but didn't work

Is there a way to do it?

EDITED:

This is my HTML:

<form role="form">
<div class="form-group">
    @Html.Label("Commentario:")
    <textarea id="Comment" style="resize:none;" class="form-control"></textarea>
</div>
<div class="form-group">
    <input type="submit" value="Guardar" onclick="AddComment(Comment.value,'Comentario')" />
</div>
</form>

EDITED 2:

Fixed by changing type="submit" for type="button" Thanks to Hasta Pasta

i think you should put return false; after the ajax request

function AddComment(commet, auto) {
    $.ajax({
        type: "POST",
        url: '/bff/SaveComment',
        data: { id: idParte, commenta: commet, autoriza: auto },
        dataType: 'json',
        success: function (correct) {
            $("#win1").show().kendoWindow({
                width: "300px",
                height: "100px",
                modal: true,
                title: "Added"
            });
        },
        error: function(inc) {
        }
    });
    return false;
}

based on you need to return false as you sayed :)

<form role="form">
<div class="form-group">
    @Html.Label("Commentario:")
    <textarea id="Comment" style="resize:none;" class="form-control"></textarea>
</div>
<div class="form-group">
    <input type="submit" value="Guardar" onclick="return AddComment(Comment.value,'Comentario')" />
</div>
</form>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM