Petr Jankovský
Petr Jankovský

Reputation: 91

How to post a form with Ajax in Razor Pages

I'm new to Razor Pages, so I'm probably asking for something very basic.

I have a Razor Page with a form, which consists of dropdown list and button. It has also one parameter, orderId as route data.

<form method="post">
        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
        <div class="form-group">
            <label asp-for="Article.Nickname" class="control-label"></label>
            <select asp-for="Article.ArticleId" class="form-control"
                    asp-items="@Model.ArticleNicknameSL">
                <option value="">-- Select Article--</option>
            </select>
            <span asp-validation-for="Article.ArticleId" class="text-danger" />
        </div>

        <div class="form-group">
            <input type="submit" value="Add Article" id="add-article" asp-page-handler="Article" class="btn btn-primary" />
        </div>
    </form>

There is a PageModel, which constits of this:

public async Task<IActionResult> OnPostArticleAsync()
    {
        if (!ModelState.IsValid)
        {
            return Page();
        }
        ArticlesInOrder newArticleInOrder = new ArticlesInOrder();

        Order = await _context.Orders
            .Include(o => o.Vendor)
            .Include(o => o.ArticlesInOrders)
                .ThenInclude(o => o.Article)
            .FirstOrDefaultAsync(m => m.OrderId == OrderId);

        Article addArticle = await _context.Articles
            .FirstOrDefaultAsync(a => a.ArticleId == Article.ArticleId);

        newArticleInOrder.Article = addArticle;
        newArticleInOrder.Order = Order;
        newArticleInOrder.Quantity = 1;
        _context.ArticlesInOrders.Add(newArticleInOrder);
        await _context.SaveChangesAsync();

        return await LoadData();
    }

This page works as intended. However, I would like post the form without postback. But I have no idea how to do this. Back in my old days with asp.net 4 (web forms), I would just put all inside tag and puff! It works. But I learned that it is not so easy these day. I was able to find this: https://www.learnrazorpages.com/razor-pages/ajax/form-post and altered the example this way:

<script>
$(function () {
    $('#add-article').on('click', function (evt) {
        evt.preventDefault();
        $.ajax({
            type: "POST",
            url: 'handler=Article',
            data: $('form').serialize(),
            headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
            success: function () {
                alert('Posted using jQuery')
            }
        }
        )

        });
    });</script>

But it does not do anything useful, just diplays the message from the alert, so I'm obviously missing something. So, what is the proper way to post a form with jquery?

Upvotes: 1

Views: 4738

Answers (1)

Petr Jankovsk&#253;
Petr Jankovsk&#253;

Reputation: 91

Okay, it is actually almost correct. All I need is add window.location.href into url:

$(function () {
    $('#add-article').on('click', function (evt) {
        evt.preventDefault();
        $.ajax({
            type: "POST",
            url: window.location.href + '?handler=Article',
            data: $('form').serialize(),
            headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
            success: function () {
                alert('Posted using jQuery')
            }
        }
        )

        });
    });

Upvotes: 2

Related Questions