6

I'm having asp. net mvc4 project. Angularjs is integrated. I have already built HTML pages and WEB APIs 2 as per previous requirements.

Now for some reason i have to go with CSHTML pages. previously I had only web api project template so i couldnt go with cshtml pages as ONLY MVC controller can return partial page(cshtml) but i was using only web apis...

So changed whole project template and so now i can have mvc controllers... ...

In short, currently I have mvc4 project with already built web apis and html pages.....

I just want to use CSHTML pages instead of using HTML pages rest things should be as they are...

Is it possible?

I may sound silly but it is need right now. help would be greatly appreciated...

Web apis, cshtml pages and angularjs only. not web apis, html pages and angularjs.

If I replace html pages by cshtml, how would angular route get affected?

Radim Köhler
  • 122,561
  • 47
  • 239
  • 335
micronyks
  • 54,797
  • 15
  • 112
  • 146

1 Answers1

4

Well, this is how I use it.

There is index.cshtml like this

@using System.Web.Optimization
@inherits System.Web.Mvc.WebViewPage
@{ Layout = null; }<!DOCTYPE html>
<html data-ng-app="MyProject">
<head>
    <title data-ng-controller="TitleCtrl" data-ng-bind="Title">My Project</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta http-equiv="cache-control" content="max-age=0" />
    <meta http-equiv="cache-control" content="no-cache" />
    <meta http-equiv="expires" content="0" />
    <meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
    <meta http-equiv="pragma" content="no-cache" />

    @Styles.Render("~/Content/min/css")
</head>
<body class="body" id="body">

    <div class="body" data-ui-view="body"></div>

    @Scripts.Render("~/js/angular")
    @Scripts.Render("~/js/MyProject")
</body>
</html>

NOTE: using angular UI-Router, that's why ui-view is in palce

But still there must be HomeController:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        // below I do some tricks to make app running on 
        // http://mydomain/app as well as on
        // http://mydomain/app/  (see the / at the end)

        var root = VirtualPathUtility.ToAbsolute("~/");
        var applicationPath = Request.ApplicationPath;
        var path = Request.Path;
        var hasTraillingSlash = root.Equals(applicationPath
                                      , StringComparison.InvariantCultureIgnoreCase)
                || !applicationPath.Equals(path
                                      , StringComparison.InvariantCultureIgnoreCase);
        if (!hasTraillingSlash)
        {
            return Redirect(root + "#");
        }

        // my view is not in Views, but in the root of a web project
        return View("~/Index.cshtml");
    }
}

So, this way I can use power of Bundle configureation (javascript, css) ... while starting angular at http://mydomain/app or http://mydomain/app/. Check also similar here

Also in global.asax, we should configura ASP.NET MVC:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.IgnoreRoute("fonts*.woff");

    routes.MapRoute(
      name: "Default",
      url: "{controller}/{action}/{id}",
      defaults: new {controller = "Home", action = "Index", id =UrlParameter.Optional}
    );
}

while web API should be:

const string IdPattern = @"\d+|[A-Za-z]{1,2}";
public static void SetRouting(HttpConfiguration config)
{
    // some custom routes
    ...            

    // and a default one
    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}"
        , constraints: new { id = IdPattern }
        , defaults: new { id = RouteParameter.Optional }
    );
Community
  • 1
  • 1
Radim Köhler
  • 122,561
  • 47
  • 239
  • 335
  • lets say I have menu which has products page. after reaching to dashboard if i click products menu list, how would it redirect me to products.cshtml page? – micronyks Dec 28 '14 at 10:36
  • right now i have set ui router like this... url:'/products', template:'/products. html' – micronyks Dec 28 '14 at 10:39
  • I extended my answer with Routing for MVC (the Home/Index) and Web API. The trick is, that while the Home / Index is loaded and the index.csthml is rendered... we do not need any redirectons. We will hav SPA... now it is Angular job to load all the views ... – Radim Köhler Dec 28 '14 at 10:39
  • I see... If you want to serve also the "Views" as .csthml you need controllers and actions for them. But I have to confirm, that after using it for most then 2 years... only INDEX.csthml is enough. The rest could be some templates in .html. Just html – Radim Köhler Dec 28 '14 at 10:40
  • Once again. You cannot add `.csthml` page!!! Clear? You **CANNOT** add `.csthml`. You can target `Controller` and `Action`... which renders `.csthml`. Is it clear now? so `products.csthml` either must be reached as `mydomain/products/list` and there must be `ProductController` with action `List()` and that will render the `products.cshtml`. **Is that clear now?** BUT what I am trying to say is: use only .csthml and homecontroller ... for your SPA page (index.cshtml). The rest could really be just .html. No need to serve that as MVC controller/action/view... do you understand me? does it help? – Radim Köhler Dec 28 '14 at 10:41
  • true. agreed. previously i had only one index.cshtml pages i was using it to inject other html views... but now it is a need to have all cshtml pages rather than having html pages.... so i wonder how would i do? – micronyks Dec 28 '14 at 10:47
  • As I said. You can do it, BUT only if there will be controller and action for each such .cshtml. Why? because runtime won't serve .cshtml to client. No way. It wll be used as a renderer for Action result. So my suggestion: DO NOT convert html to csthml for you views. no need for that. NO advantage no benefit... – Radim Köhler Dec 28 '14 at 10:48
  • so after hard work i could do something like this.... productsController. cs->index will return products. cshtml page.... n rest things as they are. this way problem is if i have 20 pages, i have to add 20 mvc controller(as per my knowlege) which seems bad approach to me..... – micronyks Dec 28 '14 at 10:51
  • YES YES. Exactly. You've got the point. SO, do not do it. Just use the index.cshtml as I showed above for start of your Angular app... I am using it for more then 2 years... and have to say... it is really ok just use .html for all the views. it will work. you will see. but there is a big benefit of having the index.html served as Home/Index and .csthml ... becuase of BundleConfig... – Radim Köhler Dec 28 '14 at 10:52
  • agreed even i used to have one index.cshtml n other html pages only.. no prbm with it. but is just said to be done so looking for some work around nothing else.... even i know it is not good approach..... – micronyks Dec 28 '14 at 11:11
  • Wish that my answer and comments helped somehow. Enjoy all these amazing features, angular, web api, bundle .. ;) good luck – Radim Köhler Dec 28 '14 at 11:19
  • @RadimKöhler you should write a blog post on this. btw which all nugets do I need to use if I just need bundling and minification as you mentioned above?? – harishr Dec 31 '14 at 13:46
  • 1
    @HarishR thanks for a nice comment! thanks. As you most likely know I use more packages through the nuget *(for example NHibernate ... ;)* so, not fully sure which are really needed just for minification... But I guess that we need all for MVC (to make *.cshtml* running there must be controller and action) `Microsoft.AspNet.Mvc`, `Microsoft.AspNet.Razor`. Maybe even `Microsoft.AspNet.WebPages` and `Microsoft.Web.Infrastructure`. Then for **Bundling** `Microsoft.AspNet.Web.Optimization` and it should require `WebGrease`. It could seem to be a lot but ... we gain: **`.Include("myscripts/*.js`** – Radim Köhler Dec 31 '14 at 14:30
  • 1
    exactly, i really never wanted to use asp.net MVC with angular, but it seems just to get the bundling/minification I will have to go with MVC, sadly – harishr Dec 31 '14 at 14:52