mr.alaa
mr.alaa

Reputation: 76

post form without refresh .net core mvc

I have a simple application in .NET Core MVC, with this simple form. When I try to post the form without refresh whole page only rest the form and got the result of done.

My code trial is:

 <form asp-area="" asp-controller="ContactUs" asp-action="UserMessage" data-ajax="true">
    <h5>Reach us quickly</h5>

    <div class="row">

        <span asp-validation-for="UserName" class="text-danger"></span>
        <div class="col-sm-6 col-12">
            <div class="form-group">
                <input asp-for="UserName" class="form-control" name="UserName" placeholder="Enter name" required="required">
            </div>
        </div>

        <span asp-validation-for="Email" class="text-danger"></span>
        <div class="col-sm-6 col-12">
            <div class="form-group">
                <input asp-for="Email" class="form-control" name="Email" placeholder="Enter email" required="required">
            </div>
        </div>
    </div>
  
    <div class="row">
        <span asp-validation-for="Msg" class="text-danger"></span>
        <div class="col-12">
            <div class="form-group">
                <textarea asp-for="Msg" name="Msg" class="form-control" rows="7" cols="25" placeholder="Message"></textarea>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-sm-12 mt-3">
            <button type="submit" class="btn solid-btn" id="btnContactUs">
                Send Message
            </button>
        </div>
    </div>
</form>

and my action is:

[HttpPost]
public async Task<IActionResult> UserMessage(ContactUs model)
{
    try
    {
        if (ModelState.IsValid)
        {
            _context.Add(model);
            await _context.SaveChangesAsync();
            return NoContent();
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
        throw;
    }

    return NoContent();
}

I want to change return NoContent(); so I can show a message to the user that his message has sent or failed, without refreshing the whole page.

Upvotes: 1

Views: 8377

Answers (4)

farshid jahanmanesh
farshid jahanmanesh

Reputation: 58

for post form without refresh ,you need to use ajax in your code.

Upvotes: 0

mr.alaa
mr.alaa

Reputation: 76

thanks for @Laz Ziya i have used his code and modify form to be

instead of

 <form method="post"
          data-ajax="true"
          data-ajax-method="post"
          data-ajax-url="@Url.Page("UserMessage", "ContactUs")"
          data-ajax-loading="#loading"
          data-ajax-mode="replace"
          data-ajax-update="#updateDiv">

to be

 <form asp-area="" asp-controller="ContactUs" asp-action="UserMessage" data-ajax-loading="#loading" data-ajax-mode="replace" data-ajax-update="#updateDiv" data-ajax-success="Success" data-ajax-failure="Failure" data-ajax="true">

Upvotes: 0

LazZiya
LazZiya

Reputation: 5719

Your form tag is missing some other ajax attributes:

<form method="post"
        data-ajax="true"
        data-ajax-method="post"
        data-ajax-url="@Url.Page("UserMessage", "ContactUs")"
        data-ajax-loading="#loading"
        data-ajax-mode="replace"
        data-ajax-update="#updateDiv">

    <!-- form controls -->

    <button type="submit" class="btn solid-btn" id="btnContactUs">Send Message</button>
    <span id="loading" style="display:none;"> <i class="fas fa-spinner fa-spin"></i></span>
</form>

<div id="updateDiv">
    <!-- ajax content will load here -->
    <!-- you can put the form inside this div -->
    <!-- so after submit the result will replace the form controls -->
</div>

<!-- include jquery libraries -->
@section Scripts {
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.unobtrusive-ajax.min.js"></script>
}

The backend method can return the result as below:

public async Task<ContentResult> OnPostUserMessageAsync(ContactUs model)
{
    try
    {
        if (ModelState.IsValid)
        {
            _context.Add(model);
            await _context.SaveChangesAsync();
            return Content("done");
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
        throw;
    }

    return Content("something went wrong...");
}

See Ajax Request Using Inline Attributes

Upvotes: 3

Jeremy Lakeman
Jeremy Lakeman

Reputation: 11100

If you don't want the page to be replaced, you'll have to use ajax to post the data via javascript. Posting a form in a browser will replace the current html with the result of the controller, that's just how forms work.

It is also common practice to redirect any successful POST to a different page, so that the user can refresh that page without processing the POST request twice.

Upvotes: 0

Related Questions