0

I have an ASP.NET MVC project and currently I am using ViewData["ResultMessage"] to show the result of a form (which is done after the user submits & refreshes the page).

I want to do it right after he clicks submit (without refreshing the page). So I have to use Javascript for that, which I am new with. No experience what so ever.

How my form looks like is this:

            <form id="contactForm" method="post" action="..">
                <div class="field half first">
                    <label for="Name">Name</label>
                    <input type="text" name="Name" id="Name" placeholder="Your name" required />
                </div>
                <div class="field half">
                    <label for="Email">Email</label>
                    <input type="email" name="Email" id="Email" placeholder="Your email" required />
                </div>
                <div class="field">
                    <label for="Message">Message</label>
                    <textarea name="Message" id="Message" rows="5" placeholder="Your message" required minlength="20"></textarea>
                </div>

                <input type="submit" value="Send Message" />
                <p>@ViewData["ContactActionResult"]</p>

            </form>

You can see the result is displayed with Razor using ViewData. Now I want to do it without refreshing the page and learn JS on the way.

What I have tried so far:

$(function () {
    $("button").click(function (e) {
        e.preventDefault()
        $.ajax({
            type: "POST",
            url: "/Receiver",
            data: car,
            datatype: "html",
            success: function (data) {
                alert("Congratulations, it worked!");
                $('#contactForm').html(data);
            },
            error: function(data) {
                alert("Failed.");
            }
        });
    });
});

But I am not sure if I did something wrong or simply not implementing it right. I have the above function inside <script> here </script> in my HTML page. Nothing happens when I click the submit button on the form.

9
  • Do you have any script errors in your console ? Open F12 dev tools - >console and check. Also what is your Receiver returning ? How does your Receiver signature looks like ? Commented May 9, 2018 at 18:47
  • First change $("button").click(function (e) to $("input[type=submit]).click(function (e) otherwise your from button is not triggering this finction Commented May 9, 2018 at 18:52
  • @slon That fixed the issue of the function not working. However, there is another issue now. After it displays the message, the entire website becomes empty (blank). The content is gone. Commented May 9, 2018 at 18:54
  • It's because you're doing this $('#contactForm').html(data); Commented May 9, 2018 at 18:56
  • You're replacing the form response html Commented May 9, 2018 at 18:57

1 Answer 1

2

If it is an ajax call, It is best if you return a JSON response . You can use the Request.IsAjaxRequest() to determine whether the request is normal form request or ajax call.

You should also consider using to the PRG pattern. After successfully saving, you should do a redirect to a GET action where you can render a view, instead of returning to the same view with a viewbag message. If you want to pass some message to the new view/action, use TempData instead of ViewData.

[HttpPost]
public ActionResult Receiver(string name, string Email)
{       
    // Your existing code to save
    if(Request.IsAjaxRequest())
    {
        return Json(new { status = "success", message = "Created successfully" });
    }
    // Normal form submit. So let's follow PRG pattern
    TempData["ResultMessage"] = "Created successfully";
    return RedirectToAction("Index");
}

You can also put a try/catch and return a json like this for error usecase

return Json(new { status = "error", message = "some serious error" });

In Index action/view, you can read TempData["ResultMessage"] and display to user.

Now, for the ajax usecase, in your current view, you can add a div to show the message

<form id="contactForm" method="post" asp-action="Receiver">

    <div id="msg"></div>

    <div class="field half first">
        <label for="Name">Name</label>
        <input type="text" name="Name" id="Name" placeholder="Your name" required />
    </div>
    <div class="field half">
        <label for="Email">Email</label>
        <input type="email" name="Email" id="Email"  required />
    </div>
    <div class="field">
        <label for="Message">Message</label>
        <textarea name="Message" id="Message" rows="5" 
                  placeholder="Your message" required minlength="20"></textarea>
    </div>

    <input type="submit" value="Send Message" />

</form>

and now in your ajax call's success callback, check the json response coming back from server and show the message property as needed. If you are putting the script inside the razor view file, make sure you are putting it inside a Scripts section so that it will be evaluated in the proper order (After jQuery is loaded, assuming you load jQuery before calling RenderSection("scripts") inside the layout)

@section Scripts
{
    <script>
        $(function (){

            $("#contactForm").submit(function (e){

                e.preventDefault()
                $.ajax({
                    type: "POST",
                    url:  $(this).attr("action"),
                    data: car,
                    success: function (data){

                        if (data.status === "success")
                        {
                            $('#msg').html(message);
                        }  
                        //to do : handle statuss=="error" as needed                                                 
                    },
                    error: function (data)
                    {
                        alert("Failed.");
                    }
                });
            });
        });

    </script>
}

For asp.net core, you can write a IsAjaxRequest method in your base controller and use that. jQuery will add X-Requested-With header with value XMLHttpRequest for your ajax calls.

protected bool IsAjaxRequest()
{
    return Request.Headers["X-Requested-With"] == "XMLHttpRequest";
}
Sign up to request clarification or add additional context in comments.

2 Comments

There is no IsAjaxRequest method in Request for me. I am using .NET Core 2 for my project.
Actually. you can implement it yourself. All it does it checking the header. I will post an update

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.