Trigger modal following unsuccessful registration

I have a method in the controller for registering users.

  [HttpPost]
    public ActionResult Register(RegisterViewModel register)
    {
        if (this.IsCaptchaValid("Captcha is not valid"))
        {

            if (ModelState.IsValid)
            {
                if (!db.Users.Any(u => u.Email == register.Email.Trim().ToLower()))
                {

                    Users user = new Users()
                    {
                        ...
                    };


                    db.Users.Add(user);
                    db.SaveChanges();

                 }
                else
                {
                     ViewBag.ErrMessage = "Error: Email Already Exist";
 
                }

             }
             else { ViewBag.ErrMessage = "Error: ModelState Is Not Valid"; }
        }
         else
         {

             ViewBag.ErrMessage = "Error: captcha is not valid.";
             return PartialView(register);
          }


        return RedirectToAction("Index", "Home");
       }

This is my script written in Razor:

 function Register() {
        $.ajax({
            type: "Get",
            url: "/Account/Register",
            contentType: "application/json;charset=utf-8",
            content: "json",
            success: function (data) {
                $('#myModal').modal('show');
                $('#myModalLabel').html('Register');
                $('#bodymodal').html(data);
            }
        });
    };
    function RegisteredSuccess(data) {
        $('#myModal').modal('hide');
        $('#MessageModal').modal('show');           
        $('#Messagebodymodal').html(data);
    }

In the view, I use this code:

@using (Ajax.BeginForm("Register","Account", FormMethod.Post,new AjaxOptions(){InsertionMode=InsertionMode.Replace,HttpMethod="post", UpdateTargetId="div", OnSuccess= "RegisteredSuccess",} ))

I display the registration partial view in a modal with the name 'mymodal' and want to show the result of the registration page in 'messagemodal' (success or failure). What is the solution?

Answer №1

One issue arises when you fail to invoke the RegisteredSuccess function.

It appears that the problem lies in calling the Rehister() function unnecessarily. The Ajax.BeginForm method handles this automatically. By simply using OnSuccess= "RegisteredSuccess", you can implement the code as shown below:

var RegisteredSuccess = function()
{
...
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Activate onbeforeunload when the form is not submitted

Currently, I have a form that is submitted using PHP with three different submit actions: Save and Continue Save and Exit Exit without Saving The goal is to trigger an "OnBeforeUnload" alert if the user does not click on any of the form actions. This al ...

Issue with AJAX functionality in MVC 5 default template

After setting up a basic MVC 5 project and integrating Entity Framework 6, I created a straightforward model class called Person with properties Id and Name. Following this, I managed to generate CRUD functionalities using the MVC 5 template post running c ...

Search for text in multiple tables using jQuery and automatically trigger a button click event when the text is found

I am attempting to query certain tables and click a button within a cell of a specific table. Below is the code I am currently using: links[1].click(); iimPlayCode('WAIT SECONDS = 2') var compTabs = window.content.document.getElementById(' ...

Techniques for transmitting stringified JSON data from the view to the controller in MVC4

I am struggling to properly send a stringified JSON object when a button is clicked. Despite being able to call the necessary Action method upon button click, the parameter is passed as null. MemberLogin.cshtml <input type="button" value="» Continue" ...

Using AJAX and jQuery to refresh a specific div when a specific button is clicked

I have a function that uses AJAX to update votes when clicked. Here is the code: $(function() { $(".vote").click(function() { var id = $(this).attr("id"); var name = $(this).attr("name"); var dat ...

Switching button class when hovering over another div

When you click on the "collapsible-header" div, I want the text "TE LAAT" in the button to change to "NU BETALEN". Currently, the CSS code changes the text on hover, but I want it to change on click when the collapsible-header also has the active class. T ...

Having trouble retrieving the JSON data received from the backend

After making an AJAX request, I receive a response which is then saved to a data variable. This is the controller logic: def retrieve data = params[:data] @question = Question.find_by(id: params[:question_id]) @choices = @question.choices results ...

A guide on retrieving nested objects from my API and parsing the resulting data in each iteration for individual elements

Struggling to update my website with a new API, specifically with accessing nested objects in a loop. Still trying to wrap my head around ajax and JSON concepts. Take a look at the API output and JS code I've been working on for a better understanding ...

Executing JavaScript code within an AJAX request

Having a problem with an AJAX function that I need help solving: PAGE A represents the main page. PAGE X represents the content loaded via AJAX. RES A represents the results from PAGE A. RES B represents the new results loaded via AJAX. PAGE A initially ...

Error: Attempting to access property 'PRM_ServerError' on an undefined object is not permitted

After deploying my code to the QA server for testing, I discovered that my image button was not triggering an event. This issue did not occur on the development server. To investigate further, I compared the console output between my local environment and ...

Ways to emphasize search outcomes in Flask/HTML?

I am currently working on creating a search box using HTML and the Flask framework in Python. Below is the layout I am working with: Layout My goal is to input text into the search box and have it highlighted within the text area on the same HTML page. F ...

Python BeautifulSoup scraping from a website with AJAX pagination

Being relatively new to coding and Python, I must admit that this question may seem foolish. But, I am in need of a script that can navigate through all 19,000 search results pages and extract the URLs from each page. Currently, I have managed to scrape th ...

The FreeTextBox Editor suddenly stopped functioning after the jquery post method was used

Thank you in advance. I have been utilizing the FreeTextBox editor within my asp.net web application, and it has been functioning well. I use a jquery Post method to populate the editor as well as other form fields with values retrieved from the database. ...

The input value in the HTML form was altered momentarily before reverting back to its original state

Researching this topic was quite challenging, but keep reading to find out why. My objective is to detect any changes in a form field so that I can enable the "Save" button. While this seems easy enough, there's a catch. If the user reverts the input ...

Prevent Fixed Gridview Header from being affected by browser Scroll-bar using JQuery

Is there a way to make the fixed header responsive to only one scroll bar in JQuery? Specifically, is it possible to have it respond solely to the div's scroll bar and not the browser's scroll bar? I attempted to remove the browser's scroll ...

Choosing data based on specific conditions in a database using PHP when the $_POST array is empty and contains a

I am having trouble selecting data from my database using PHP and an ajax call function. In the select function, I am using $_POST to retrieve data from a textbox. Even though I have set up a PHP and ajax call function on my page, something seems to be goi ...

Enabling remember me feature during ajax authentication in Laravel

Currently in the process of rebuilding my system using Laravel 5.4. I have successfully implemented an AJAX login feature, but now I am looking to add the "remember" option to the authentication process. According to the documentation, this is how you set ...

When the button is clicked, the form will be submitted regardless of the button type

When submitting a form with ajax using vuejs, everything works fine except for the issue where pressing enter in the input field submits the form to itself. Despite using `form role=form` and `button type=button`, even when the button is outside the form, ...

Using C# to send HttpWebRequest with a JSON POST request header

While translating a JSON API into C# Methods, I came across an issue with the JSON RPC API (POST) that states: All other methods require the result from authentication ( = sessionId), either through a path parameter ;jsessionid=644AFBF2C1B592B68C6B04938B ...

adding new information through a downward animation

I am trying to implement a slide down effect using jQuery to display data. Can anyone provide guidance on how to achieve this? Below is the code I have so far: function cart(idx, jml) { var jumlah = $("#" + jml).val(); $.ajax({ type: "GET", ...