MVC 5, angularJs, Actionmethod does not redirect to the view - angularjs

I am working on an MVC5 + angularJS project.
I have an angularjs code that hits MVC controller. And I expect the view to show. But The view does not come up. the screen remains the same.
My MVC method:
[HttpGet]
public ActionResult InitiatePayment()
{
string strForm="";
return View(model: strForm);
}
When I access the controller from URL the view comes up.
But when I access the method from angularJs method, the view does not come up. The old screen remains as it is. There are no error thrown either.
My angularJs code:
payment.factory("PaymentService", function ($http) {
return {
getSearchresult: function ( callback) {
return $http.get("/Payment/MigsPayment/InitiatePayment/").success(callback);
}
}
});
When I type in the browser:
http://localhost:52095/Payment/MigsPayment/InitiatePayment
the IntiatePayment view comes up. So what am I missing or making mistake?

Related

How to pass data between angular controllers through mvc controller

I have an angularjs controller which i wanted to pass data to other angularjs controller, and here i am not using angularjs routing, only using MVC routing,
As i am using MVC Routing, i had passed data from angularjs controller to MVC controller action method, and from there i have to return to another angularjs controller, i am unable to pass data to the other controller or even it is not returning to the MVC routed View(), and in angularjs controller i used $window.location.href to rediect to the expected view, But unablt to pass data
AngularJS Controller
$http.post(attserviceBasePath + '/Dashboard/PostMembers', group)
.then(
function (response) {
window.location.href = attserviceBasePath + '/Attendance/Dashboard/GroupedTeamMembers';
}, function (error) {
//console.log(error);
});
MVC Controller:
[HttpPost]
public ActionResult PostMembers(GroupedMembers grpMembers)
{
var result = grpMembers;
return RedirectToAction("GroupedTeamMembers", result);
}
public ActionResult GroupedTeamMembers(GroupedMembers grouped)
{
return View(grouped);
}
it is not working ...
please help me to pass data from one angularjs controller to another angularjs controller through MVC controller...
Thanks In Advance.......
You have to use sessions to pass data between controllers. check this one ex

Redirecting to html page from Spring Controller class

I am using angularjs and spring mvc for my application.I am doing payment gateway integration.The issue i am facing is after successful transaction or failure i need to redirect to html page.But right now i am not able to do so.
Here is the SpringController.java
#RequestMapping(value="/getDonationDetails",method={RequestMethod.GET,RequestMethod.POST})
public #ResponseBody String getDonationDetails(#RequestParam String msg) throws IOException {
if(updateTransaction!=null){
return "redirect:/donate";
}else{
return "redirect:/donate";
}
}
Right now i am using redirect.But it is displaying "redirect:/donate' in an empty page.
Here is my angular app.js code
$routeProvider.when('/donate',{
templateUrl : 'static/front/donate.html',
controller : DonateController
});
Can anyone tell how to redirect to donate.html page from return statement?

URL is showing MVC controller name twice

I am working with .net mvc and angular js.
HomeController
public ActionResult Index()
{
return View();
}
In angular controller there is a service to get all the item details
[HttpGet]
public JsonResult GetItemDetails()
{
// return item list
}
If I run the solution without opening HomeController in visual studio I found 404 error saying that resource is not found.
One more thing I have noticed in network is the called URL is "/Home/Home/GetItemDetails".
But when I open HomeController in visual studio everything will be working fine.
How it is happening ?
Make sure your routing values and the URL you called are one and the same.
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
For this, the URL looks like /Home/Index
Verify the URL you are using in Angular and you may be adding the controller name twice somewhere.
$http.get("Home/GetItemDetails") this is the URL I had used to call controller method.
I missed slash in this
So the solution is $http.get("/Home/GetItemDetails")
Thank you.

AngularJS controller is not reaching webapi

In the interest of crawling before walking with angularjs, I have created a simple application to display results from a sql server table using webapi. unfortunately the webapi is never called, because the routing is wrong, but I am not sure how to resolve. fiddler shows a 404 error.
the cshtml is as follows, defining the app and controller.
<script type="text/javascript">
var app = angular.module('streamApp', []);
app.controller('streamController', function($scope, $http){
$scope.loading = true;
$scope.addMode = false;
//Used to display the data
$http.get('/api/Stream/').success(function (data) {
$scope.streams = data;
$scope.loading = false;
})
.error(function () {
$scope.error = "An Error has occured while loading streams!";
$scope.loading = false;
});
});
</script>
the rendering section in the cshtml file is
<div data-ng-app="streamApp" data-ng-controller="streamController" class="container">
....
</div>
The webapi class is in a folder named WebApi in the MVC project, but since it is never reached, there is no point in displaying its code. it is non-descript anyway.
The route config is as follows:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
I am not sure if I need to specify route instructions in angularjs code or in mvc route config, and exactly what functions or configuration to supply. I have tried moving the webapi class to the Controllers folder with the same results - http 404. Any advice on how to make this example get to the webapi code would be appreciated.
well hot-diggity....I solved the immediate problem by adding the annotation to my webapi class method
[Route("api/stream")]
[System.Web.Http.HttpGet]
public IEnumerable<Models.StreamViewModel> Get()
{
.....
}
so now the question is should something be done with RouteConfig as a better practice? Or is the Route() annotation the preferred way to go? or is it 6 of one half a dozen of the other?
Answer to your updated question , Best Practice of routing:
Route() annotation is the preferred way of doing this.
MVC 5 supports a new type of routing, called attribute routing. As the
name implies, attribute routing uses attributes to define routes.
Attribute routing gives you more control over the URIs in your web
application.
The earlier style of routing, called convention-based routing, is
still fully supported. In fact, you can combine both techniques in the
same project.
There are other advantages of attribute routing like
It puts the route information adjacent to the controller action that
implements that route. This helps in debugging and troubleshooting,
as well as providing an ability to quickly search for route
information in your solution.
It reduces risk in the process of making changes to routes. In RouteConfig.cs or WebApiConfig.cs (in the case of Web API solutions),
the possibility exists to inadvertently change the wrong route or
otherwise adversely affect other parts of your application.
You may also want to include acceptable HTTP methods, permitted user types and registration priorities, which if included with the
attribute-based routes, put all of that information together in one
place.
This post provided inspiration and reinforcement for me on the above, and goes into more detail:
http://kevinmontrose.com/2011/07/25/why-i-love-attribute-based-routing/
You can use either, but without the annotation your endpoint would have been api/get not api/stream (assuming you didn't rename your method).
First , you should use ApiController rather then Controller, as it take a role of an api action.
Second, If we take a look, it looks like you created a controller named ApiController, and a function called Stream. Otherwise, its a misunderstanding of the designing your web integration using MVC.
App_Start\WebApiConfig.cs:
using System.Web.Http;
class WebApiConfig
{
public static void Register(HttpConfiguration configuration)
{
configuration.Routes.MapHttpRoute("API Default", "api/{controller}/{action}/{id}",
new { id = RouteParameter.Optional });
}
}
Global.asax.cs:
using System.Web.Http;
...
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
WebApiConfig.Register(GlobalConfiguration.Configuration);
RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
and ApiControllerNameController: //The Controller word closes the file name, and will be reached without writing it:
using System;
..
..
..
namespace MvcApplication1.Controllers
{
public class ValuesController : ApiController
{
// GET api/values/MethodName
public IEnumerable<int> MethodName()
{
return new List<int> { 1, 2, 3 };
}
}
}

Unified MVC Controller Routing in Asp.Net 5

During my working in ASP.NET 5, I am confused in some of the unified controller concepts. Please show me what I doing wrong.
In ASP.NET 5 the same controller is used for MVC and WebApi with only the difference of Routing attribute defined above a Web Api controller. My thoughts is that the "Route" attribute is only used to define a route. But there has been some occurances that defining "Route" attribute at the top is specifing a controller to be a Web Api controller.
In Startup.cs, I have the following routing configurations.
app.UseMvc(routes => {
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
routes.MapWebApiRoute(
"DefaultApi",
"api/{controller}/{id?}");
});
In Home Controller, there is "HttpGet" action for accepting WebApi get request, but it cannot be called without "Route" attribute, however the routing for the web api is already defined in the startup class.
public class HomeController : Controller {
public IActionResult Index() {
return View();
}
//[Route("api/[controller]")]
[HttpGet]
public IEnumerable<string> Get() {
return new string[] { "value1", "value2" };
}
}
And in Values controller, "About" action can't be accessed as the call to "/values/about" will give an error not found. And "/api/values/about" will redirected to the "Get" action.
[Route("api/[controller]")]
public class ValuesController : Controller {
public IActionResult About() {
ViewData["Message"] = "Your application description page.";
return View();
}
// GET: api/values
[HttpGet]
public IEnumerable<string> Get() {
return new string[] { "value1", "value2" };
}
}
But although I have specified the web api route in startup.cs file, I cant access the "/api/home" path.
What am I doing wrong?
I believe you are mixing different routing methods.
Because the controllers are unified, you do not have to specify a route for webapi and another one for MVC.
The MapWebApiRoute function is only for backwards compatibility with code written for the older WebApi 2 ASP.NET.
If you want to use the convention based routing, you can just leave the UseMvc empty like this:
app.UseMvc();
For a thorough explanation of the different options, please see this useful blogpost: ASP.NET 5 Deep Dive: Routing.
Also see this question about the non-existing differences between MVC and WebApi Controllers in ASP.NET 5.

Resources