How do I call a method using AJAX inside a form?

In this shaver mode, I have two buttons called previous and next. When the user clicks these buttons, I need to call the method where the custom type is stored:

@using (Html.BeginForm("Index", "Quiz", FormMethod.Post))
{
<div style="border-bottom: 2px solid #c8c8c8; overflow: auto; width: 100%">
    <h2 class="float-left" style="padding-bottom:5px;">@Model.Quiz.Name</h2>

    <div class="float-right">
        <input name="button" type="submit" value="done" />
    </div>
</div>

@for( ...) {
...
}

<div class="fixednavcontainer">
    <div id="questionnav" class="content-wrapper">
        <div id="questionnavstatus" class="float-left">
            <p>
                Question <span id="currentPage">@ViewBag.CurrentPage</span> of <span id="totalPages">@ViewBag.TotalPages</span>
            </p>
        </div>

        <div id="navbuttons" class="float-right">
            <img id="previous" src="~/Images/previous.png" />
            <img id="next" src="~/Images/next.png" />
        </div>

        <div class="clear-fix" />
    </div>
</div>

      

Something like this should call buttons

private void Save(@model model)
{
    ...
}

      

I would like ajax to not update anything on the page or load another page, just save and keep the same page. Is it possible to do this by calling an action method with jquery (I think)?

+3


source to share


2 answers


You can also use jQuery and make the call like this:

var myModel = @Html.Raw(Json.Encode(MyModel));  //MVC3

$.ajax({
    type: "POST",
    url: "/MyController/SomeAction/",
    data: myModel ,
    cache: false,
    dataType: "json",
    success: function (response) {
        // Do whatever you have to do...
    }
});

      



And in your controller, something like this:

public class MyController
{
    [HttpPost]
    public ActionResult SomeAction(MyModel myModel)
    {
        // Do whatever and return whatever
            return true;
    }
}

      

+3


source


You can just

$.ajax({
    type: "POST",
    url: "@Url.Action('yourAddress')",
    data: parametr,
    cache: false,
    dataType: "json",
    success: function (response) {
        // Do whatever you have to do...
    }
});

      



and in the controller

public class XController
{
    [HttpPost]
    public ActionResult yourAddress(YourModel)
    {
...
    }
}

      

+2


source







All Articles