How to redirect to a different view or controller using ASP.NET and AngularJS

How can I open the View located at /Home/CreateItem after clicking on the Add button? What do I need to include in my code?

$scope.Add = function() {
        console.log('working');
    }

This is how Index.cshtml looks like:

<script src="~/Scripts/jquery-1.9.1.min.js"></script>
<script src="~/Scripts/angular.js"></script>
<script src="~/Scripts/MyScript/Custom.js"></script>
<script src="~/Scripts/angular-animate/angular-animate.min.js"></script>
<script src="~/Scripts/angular-ui/ui-bootstrap.min.js"></script>
<script src="~/Scripts/angular-ui/ui-bootstrap-tpls.min.js"></script>

<div ng-controller="Second">
    <button ng-click="Add()">Add</button>
</div>

HomeController code:

namespace MvcApplication6.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            return View();
        }

        public JsonResult GetData()
        {
            string data = "From controller";
            return Json(data, JsonRequestBehavior.AllowGet);
        }

        public ActionResult CreateItem()
        {
            return View();
        }
    }
}

And here's a snippet from Controller.js:

var app = angular.module('MyApp', ['ngAnimate', 'ui.bootstrap']);
app.controller('Second', function ($scope, sharedProperties) {
    $scope.Add = function() {
        // How do I redirect to Home/CreateItem?
    }
});

Answer №1

Alright

app.controller('SecondController',["$http","sharedProperties","$location", function ($scope, sharedProperties,$location) {
    $scope.addItem = function() {
$location.path("/Home/CreateItem");
    }
}]);

Improvement

app.controller('SecondController',["$http","sharedProperties","$location", function ($scope, sharedProperties,$location) {
    $scope.addItem = function() {
$location.path("/Home/CreateItem");
    }
}]);

The Improvement method is more effective as it allows for minifying your angular code. By explicitly declaring that you expect $http as param 1 and sharedProperties as param2, a minifier can rename those variables to x and y, reducing the size of your javascript file.

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

Navigate directly to a designated element in a React component without the need to scroll when clicking a link

When viewing a user's profile in React, clicking on an image currently scrolls to that specific image within the entire images page. However, I am looking to modify this behavior so that it navigates directly to the image element without any scrolling ...

having difficulty sorting items by tag groups in mongodb using $and and $in operators

I'm currently trying to execute this find() function: Item.find({'tags.id': { $and: [ { $in: [ '530f728706fa296e0a00000a', '5351d9df3412a38110000013' ] }, { $in: [ ...

The Firebase JQuery .on method is incrementally updating individual values in an array instead of updating them all simultaneously

I am trying to update the values of the orders placed by users on the Corporate's page without a refresh. I have implemented the jQuery .on method for this purpose. However, the values are being returned one by one from the array created for the order ...

Restoring styles back to the default CSS settings

I am currently working on creating visualizations using D3, and one challenge that I have encountered is the need to define a lot of styles within my code instead of in my CSS where I would prefer them to be. This necessity arises mainly to support transi ...

Difficulty in transmitting two boolean values using ajax and setTimeout()

I am working on two functions that are supposed to send either 0 or 1 to a PHP page using AJAX. When a key is pressed on the keyboard, the function that sends 1 should start, followed by the second function that sends 0 three seconds later using setTimeout ...

The JSON response is being overridden by a catch-all URL and ends up being displayed as a 404 error page

I'm dealing with a React/Express setup that looks something like this (simplified for clarity): const path = require('path') const express = require('express') const CLIENT_BUILD_PATH = path.join(__dirname, '../build') ...

What is the best way to transmit a JSON object to REST services using Angular?

Whenever I attempt to send the JSON object to REST services, I encounter an error that looks like this: http://localhost:8080/api/v1/cardLimit 400 (Bad Request); JSON Object Example: public class GameLimit implements Serializable { private stati ...

How to toggle the visibility of a div with multiple checkboxes using the iCheck plugin for jQuery

I customized my checkboxes using the icheck plugin to work with both single and multiple checkboxes, including a "Check all" option. Here is an example of how it looks in HTML: HTML : <div>Using Check all function</div> <div id="action" c ...

Node.js making an API request

I am encountering an issue with the following code snippet: const req = require("request"); const apiReq = req("http://example.com/car/items.json", (err, res, body) => { if (!err && res.statusCode === 200) { return JSON.parse(body); } } ...

The functionality of switching between two layouts using a JavaScript button is currently not functioning

My concept involves implementing a switch that alternates between displaying a bootstrap carousel and cards. Essentially, one of them will be visible when the button is pressed while the other remains invisible. Initially, I am attempting to hide my existi ...

To activate a function, simply click anywhere on the body: instruction

One of my latest projects involved creating a directive that allows users to click on a word and edit it in a text box. Once edited, clicking anywhere on the body should return the word back to its updated form. html <div markdown>bineesh</div& ...

Building a loading bar using dots

<span class="dot"></span> <span class="dot"></span> <span class="dot"></span> <span class="dot"></span> <span class="dot"></span> <span class="dot"></span> <span class="dot">< ...

Identifying all elements with querySelectorAll and monitoring events with

I am currently attempting to modify this demonstration for page transitions triggered by clicking on links with a shared class. Despite following @ourmaninamsterdam's suggestion here, I am facing difficulties in getting the transitions to work. Can yo ...

Choosing between radio buttons either horizontally or vertically within a table

Here is the markup I am working with: <table> <tr> <td><input type="radio" name="radio"></td> <td><input type="radio" name="radio"></td> <td><input type="radio" name="radio"></ ...

What is the most effective method for retrieving a key and value from an Axios response object?

I currently have a Mongoose schema set up to store key:value pairs in a mixed type array, represented like this: Mongoose const budgetSchema = new Schema({ earnings: Number, expenses: [mongoose.Schema.Types.Mixed] }); budget:{ earning:1000, exp ...

Creating separate chunks for individual files in Vue CLI3JsonPropertyTitleFileType

I am working on a project using vue-cli3 and need to separate out a specific file for chunking due to IIS requirements. Currently, webpack chunks files based on default settings and also automatically creates chunks from dynamic imports in vue-router. How ...

Redis: Unable to establish a connection as net.connect is not recognized as a

I'm struggling to integrate Redis with nodejs Encountering issues during execution Despite using the same code, I am facing this error: Here's my code snippet: import { createClient } from 'redis' export const client = createClient({ ...

I am unable to generate a vite application within WSL

My system is running node version 10.19.0 and npm version 6.14.4. Whenever I try to run create-vite@latest client, I encounter the following error: npx: installed 1 in 0.79s /home/victor/.npm/_npx/86414/lib/node_modules/create-vite/index.js:3 import &apos ...

Retrieving text from a draggable div using jQuery

I have a draggable div that I can move over another element with the class .outerDiv which contains text content. Is there a way for me to retrieve the text from .outerDiv that overlaps with the draggable div? $(".outerDiv .isStore").draggable({ contain ...

Developing an ASP application using the MVP pattern to return JSON data can be transformed into a S

I’m looking to incorporate the following code into a sails js Controller public JsonResult GetEvents() { //Using MyDatabaseEntities as our entity datacontext (refer to Step 4) using (MyDatabaseEntities dc = new MyDatabaseEntities()) { ...