Using ajax javascript to render a view in ASP.NET MVC

When I attempt to use Ajax Javascript to call Action and open my Index View, the target view does not load. Before using ajax, I called the action like this and it worked properly:

<a class="btn btn-orange" href="@Url.Action("Index", "Booking", new { area = "Portal" })">انتخاب</a>

However, when I tried to call it with javascript Ajax by transferring it to this:

<a class="btn btn-orange" onclick="Booking(@Json.Encode(item))">انتخاب</a>

I encountered a problem where the page does not load. Here is my ajax code:

function Booking(obj) {
    var schedulingViewModel = {
    };
    for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
            schedulingViewModel[key] = obj[key];
        }
    }
    $.ajax({
        url: '/Portal/Booking',
        type: 'post',
        data: schedulingViewModel,
        success: function (data) {
            alert('Data: ' + data);
        },
        error: function (request, error) {
            alert("Request: " + JSON.stringify(request));
        }
    });
}

And this is my BookingController:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Tranship.ViewModel;

namespace Tranship.UI.Areas.Portal.Controllers
{
    public class BookingController: Controller
    {
        [HttpPost]
        public ActionResult Index(ScheduleViewModel schedulingViewModel)
        {
            return View("Index", schedulingViewModel);
        }
    }
}

This is my view with IEnumerable model that I want to send an Item of that to action:

@model IEnumerable<Tranship.ViewModel.ScheduleViewModel>
<div class="pg-search-form">
    @foreach (var item in Model)
    {
        <div class="list-block main-block f-list-block dashboard-listing booking-listing">
            <div class="list-content">
                <table class="table table-hover">
                    <tbody>
                        <tr>
                            <td class="dash-list-icon booking-list-date">
                                <div class="b-date">
                                    <h3>@item.DepartureDay</h3>
                                    <p>@item.DepartureMonth</p>
                                </div>
                            </td>
                            <td class="dash-list-text booking-list-detail">
                                <h3>@item.Origin به @item.Destination</h3>
                                <ul class="list-unstyled booking-info">
                                    <li>@item.DepartureDate<span>تاریخ رفت :</span></li>
                                    <li>@item.ArrivalDate<span>تاریخ برگشت :</span></li>
                                    <li>@item.Adult نفر<span>تعداد :</span></li>
                                </ul>
                            </td>
                            <td class="dash-list-btn">
                                <a class="btn btn-orange" onclick="BookingMethod(@Json.Encode(item))">انتخاب</a>
                                <div id="price">@item.Price تومان</div>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
            <!-- end list-content -->
        </div>
    }
    <div class="pages">
        <ol class="pagination">
            <li><a href="#" aria-label="Previous"><span aria-hidden="true"><i class="fa fa-angle-left"></i></span></a></li>
            <li class="active"><a href="#">1</a></li>
            <li><a href="#">2</a></li>
            <li><a href="#">3</a></li>
            <li><a href="#">4</a></li>
            <li><a href="#" aria-label="Next"><span aria-hidden="true"><i class="fa fa-angle-right"></i></span></a></li>
        </ol>
    </div>
    <!-- end pages -->
</div>

The ajax response provides correct HTML, but I have yet to determine why it's not redirecting to the target view.

Answer №1

window.location() is commonly utilized for page redirection.

Implement the following code after a successful ajax request:

 $.ajax({
    url: '/Portal/Booking',
    type: 'post',
    data: schedulingViewModel,
    success: function (data) {
        alert('Data: ' + data);
        window.location = "/Booking/Index";
    },
    error: function (request, error) {
        alert("Request: " + JSON.stringify(request));
    }
});

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

When attempting to execute the npm install command within Visual Studio Code, an error message is being displayed

[ Windows PowerShell Copyright (C) Microsoft Corporation. All rights reserved. Explore the new cross-platform PowerShell https://aka.ms/pscore6 PS C:\Users\sahib\Downloads\generative-art-node-main (1)> npm install npm ERR! code ENO ...

After successfully posting a tweet, I have not heard back from Twitter

My objective is to achieve the following on click: Share the URL and text on Twitter in a popup window Receive a response from Twitter indicating whether the tweet was successful or failed Close the popup window after the tweet is successfully pos ...

Utilizing the Command Line/Window feature within Visual Studio Code

As a newcomer to Visual Studio Code, I'm currently using the latest Version: 1.29.1. When I used Matlab, I had access to a script window for writing code, a Command Window for testing code snippets and viewing variable values, as well as a workspace ...

Dynamic addition of CSS classes to HTML elements using PHP

I'm working on developing an application that includes multiple courses. Each course is completed over a certain number of days, such as 14 days or 20 days. To visually track progress, I've implemented a step progress bar that looks like this:htt ...

Incorporating Advanced Custom Fields (ACF) for a Tailored Search Functionality on WordPress

My latest blog feature is a custom search function that uses Ajax to load results without refreshing the page. It searches through a specific category and displays all posts, regardless of the search term. Within my page, I utilize Advanced Custom Fields ...

Solving the Issue of Losing Object Instance During Redirect After Authorization in ASP-MVC

I am facing an issue with the "Authorize" attribute on the Action that binds the form data. After submitting the form, if the user is not authorized, the login prompt shows up. Upon successful login, the user gets redirected correctly, but the model turns ...

Hello, I have been working on implementing Mern Stack authentication for the past two weeks but I am still struggling to resolve a persistent error

An error message is displaying on the server stating: Server running on port 5000 Error: MongooseError: The uri parameter for openUri() must be a string, it is currently set as "undefined". Ensure that the first parameter in mongoose.connect() or mongoose ...

Steps to employ ajax to fire a PHP function that saves data into an array

Currently, I am utilizing a Mysql table along with PHP to display data on a webpage. Each data value is accompanied by a button that, when clicked (each with a unique ID), triggers an AJAX call to activate a PHP function which then adds the button's I ...

Creating a JSON object using JavaScript for sending to a PHP script

I'm working on a form that contains radio buttons as options. To send the selected radio button values to a PHP script, I need to construct a JSON object for posting. Although I've attempted to create the necessary code, I'm uncertain about ...

Determine the length of a string in JavaScript and PHP taking into account "invisible characters" such as and

I have a textarea where users can input text, and I want to show them how many characters they have left as they type using JavaScript or jQuery: var area = 'textarea#zoomcomment'; var c = $(area).val().length; After that, the text is validated ...

Getting data from components in React: A step-by-step guide

As a newcomer to Reactjs, I find myself working on an existing project where I am attempting to retrieve product reviews using components. However, my console currently displays 0 reviews. How can I resolve this issue? The file in question is "pages/[slug ...

CSS selectors following an ajax request (commenting system)

Issue: After submitting a comment on a webpage, the comments are not displaying correctly. I want them to slide down below the last added comment. It seems to be related to CSS selectors. Can someone help me figure out which selector I need to use? Any a ...

How to Assign List Load to Controller for Google Maps?

I find myself in a predicament where I am required to retrieve the list in my Controller, but currently I am utilizing a Kendo Grid to fetch the list that will be utilized in my Google Maps. Now, my questions are: How can I directly associate the Load ...

Error: unable to render image data type on ASP.NET webpage

I'm facing an issue with displaying SQL image data on an asp.net page. The string I'm getting doesn't seem to work and I can't figure out why. Here is the model I'm using public partial class GetEmployeePhoto2_Result { public ...

Issue with Vuex map state being undefined when called from a component

Recently, I've been working on updating data in a component every time the Vuex state is not null. I have set up API routes with Laravel that return user information once they are logged in. API routes: Route::group(['middleware' => [&a ...

What are the factors that lead to the rendering of an Angular component?

Efficiency is key in maximizing performance with single page applications. Take, for example, React, where any change in state or props within a component triggers a re-execution, re-evaluation, and ultimately, a re-rendering of that component. With that ...

The response object from jQuery AJAX is showing undefined keys when logging on the console

Selected response by Rohan Kumar: Modified $.post() to $.post("monitor/loadEVents", function(data){ if(data && data.response){ console.log('Wow, it works.'); } else { console.log(data); } ...

Animating CSS styles in Vue.js based on JavaScript triggers

Within my Vue.js application, I've implemented a login form that I'd like to shake whenever a login attempt fails. Though I have achieved the desired shaking effect, I'm not completely satisfied with my current solution. Here's a simpl ...

The code is throwing a SyntaxError because it encountered an unexpected character in the JSON file at position 650xx

I am encountering an issue when attempting to save a JSON-formatted file from within the Javascript app I am developing. The app is running on Node v6.11.0 with Express on my local machine, port 3000. Occasionally, I come across the following error: Synta ...

What is the best way to retrieve an HTTP response within a JavaScript function once it has been received

I am looking for a solution to call a function and pass the response rendered to an express-handlebars page. Can someone guide me on how to achieve this? In my controller, I have code that renders the result to a handlebars page: return servico.obter ...