angularjs with cshtml page only not html pages with web api 2 - asp.net-mvc

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?

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 }
);

Related

Standalone Blazor app as a Razor Class Library

Is it possible technically to have a full webassembly Blazor application as a Razor Class Library and then consume it in another ASP.NET project regardless of the consumer be MVC, Razor Pages, or Blazor app? Is it possible to define the routing within the Razor Class library?
I'm working on a project that is going to be published as a Nuget package. This package should be used in a variety of ASP.NET projects which are implemented as MVC, Razor Pages, or even Blazor.
I figured out how to get it running. I am using .NET 5.0.
First create a new Solution with a Razor Class Library project (Check the checkbox Support pages and views).
And create a MVC project.
In Startups.csadd the following:
public void ConfigureServices(IServiceCollection services)
{
...
services.AddRazorPages();
services.AddServerSideBlazor();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
...
app.UseEndpoints(endpoints =>
{
endpoints.MapBlazorHub();
endpoints.MapRazorPages();
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
Also make sure you have app.UseStaticFiles(); in your Configure method.
Then, in your Razor Class Library, you can copy and paste the Pages, Shared folders and all other razor files from the example Blazor webassembly project. Also don't forget the wwwroot css folder and add your own wwwroot folder to your RCL.
In the Pages folder also create a new cshtml file. This will be the entry point to your Blazor app.
Example code:
#page
#using PROJECTNAME
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Blazor WebAssembly Prerendered</title>
<base href="~/" />
<link href="/_content/PROJECTID/css/bootstrap/bootstrap.min.css" rel="stylesheet" />
<link href="/_content/PROJECTID/css/app.css" rel="stylesheet" />
#*https://learn.microsoft.com/de-de/aspnet/core/blazor/components/css-isolation?view=aspnetcore-5.0#razor-class-library-rcl-support*#
<link href="/_content/PROJECTID/PROJECTNAME.bundle.scp.css" rel="stylesheet" />
</head>
<body>
<app>
<component type="typeof(App)" render-mode="ServerPrerendered" />
</app>
</body>
</html>
<script src="_framework/blazor.server.js"></script> <!--blazor.webassembly.js didn't work-->
The important parts are the <base href="~/" /> and the _framework/blazor.server.js.
If you don't map this page to be at the root, like #page "/" you have to make sure all the static content is mapped to the project-id correctly.
Also make sure the paths in the example projects NavMenu.razor are correct if you don't use / as the root. Has to be correct in the Razor Components too.
If you have problems with the _Imports.razor file, try adding the NuGet package Microsoft.AspNetCore.Components.WebAssembly
Also add the correct namespace for your shared folder, in the example project it's PROJECTNAME.Shared. Change it accordingly.
Here's a blogpost that helped me get things the right way: https://blog.joelving.dk/2020/02/reusable-ui-and-interchangable-hosting-models-in-blazor/

Partial file not found in mvc application

I am getting following error.
An exception of type 'System.InvalidOperationException' occurred in System.Web.Mvc.dll but was not handled in user code
Additional information: The partial view '../Shared/Partial/_ReferencePartial.cshtml' was not found or no view engine supports the searched locations. The following locations were searched:
I am having login controller in Area/Admin. In Login.cshtml view file, I am referencing Partial View file that contains references to script files. This file is in the folder, Solution/Project/Views/Shared/Partial.
Below is my Login.cshtml view file code.
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>#Messages.Login</title>
#Html.Partial("../Shared/Partial/_ReferencePartial.cshtml")
</head>
...
If you want to load the partial view directly inside the main view you could use the Html.Action helper:
#Html.Action("Load", "Home")
or if you don't want to go through the Load action use the HtmlPartial hepler:
#Html.Partial("_LoadView")
If you want to use Ajax.ActionLink, replace your Html.ActionLink with:
#Ajax.ActionLink(
"load partial view",
"Load",
"Home",
new AjaxOptions { UpdateTargetId = "result" }
)
and of course you need to include a holder in your page where the partial will be displayed:
<div id="result"></div>
Also don't forget to include:
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
in your main view in order to enable Ajax.* helpers. And make sure that unobtrusive javascript is enabled in your web.config (it should be by default):
<add key="UnobtrusiveJavaScriptEnabled" value="true" />

Index ActionMethod in Home Controller would be called twice in ASP.Net MVC

i created an ASP mvc 4 project with basic template and just with one Index view .
when i run the application , Index Method that belongs to Home Controller called twice.
i cant understand why
please help me
Thanks Alot
Index Method:
public ActionResult Index()
{
return View();
}
Index View :
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
</body>
</html>
finally i found the problem
i always test my project on google chrome after changing browser and agin run the project on IE it did not occour the problem again
so my browser which was set in VS2012 , and its setting was the problem

Getting Angular UI Directives for Bootstrap up and running with MVC

I am trying to get Angular UI Directives for bootstrap working with ASP MVC.
I have created a new, basic project and have used Nuget to add Twitter Bootstrap, AngularJS and UI Bootstrap.
I am registering these as bundles like so:
bundles.Add(new StyleBundle("~/Content/bootstrap")
.Include("~/Content/bootstrap.css")
.Include("~/Content/bootstrap-theme.css"));
bundles.Add(new ScriptBundle("~/bundles/angular")
.Include("~/Scripts/angular.js"));
bundles.Add(new ScriptBundle("~/bundles/angularUiDirectives")
.Include("~/Scripts/ui-bootstrap-{version}.js"));
My shared _Layout.cshtml page looks like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Testing Angular - #ViewBag.Title</title>
#Styles.Render("~/Content/css")
#Styles.Render("~/Content/bootstrap")
#Scripts.Render("~/bundles/modernizr")
</head>
<body>
#RenderBody()
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/angular")
#Scripts.Render("~/bundles/angularUiDirectives")
#RenderSection("scripts", required: false)
</body>
</html>
So I have added the libraries for Angular UI directives, along with the dependencies listed here via Nuget, I am registering all of these libraries as bundles and then I am rendering these bundles on my shared master page.
So far so good, but then I get to the next instruction:
As soon as you've got all the files downloaded and included in your page you just need to declare a dependency on the ui.bootstrap module
What does 'declare a dependency' mean in regards to HTML and CSS? The page on github suggests I need to put the following somewhere:
angular.module('myModule', ['ui.bootstrap']);
Where do I put this, and when do I run it?
Thanks
I solve this by doing the following:
I added the following to the opening HTML tag of my master page (replacing appName with the name of your application):
ng-app="appName"
I created a seperate Javascript class which I called test.js, registered this as a bundle and added the following:
angular.module('appName', []);
angular.module('appName', ['ui.bootstrap']);
The first line defines the angular module, the second wires it up to the UI Bootstrap library, and you need both.
Updated code to register my bundles is below:
using System.Web.Optimization;
namespace MvcApplication2
{
public class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new StyleBundle("~/Content/bootstrap")
.Include("~/Content/bootstrap.css")
.Include("~/Content/bootstrap-theme.css"));
bundles.Add(new ScriptBundle("~/bundles/angular")
.Include("~/Scripts/angular.js"));
bundles.Add(new ScriptBundle("~/bundles/angularUiDirectives")
.Include("~/Scripts/ui-bootstrap-tpls-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/test").Include("~/Scripts/Test.js"));
}
}
}
Here is the code for Test.js:
angular.module('appName', []);
angular.module('appName', ['ui.bootstrap']);
Here is the code for my master page:
<!DOCTYPE html>
<html ng-app="appName">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Testing Angular - #ViewBag.Title</title>
#Scripts.Render("~/bundles/angular")
#Scripts.Render("~/bundles/angularUiDirectives")
#Scripts.Render("~/bundles/test")
#Styles.Render("~/Content/bootstrap")
</head>
<body>
#RenderBody()
#RenderSection("scripts", required: false)
</body>
</html>
At this point we are fully setup with AngularJS, and Twitter Bootstrap and Angular Directives for Bootstrap in an ASP MVC application.

Mvc3 web app routing directly on index.cshtml

I have created and host nvc3 web app
now problem is when I open my www.abc.com
it is opening index.cshtml i.e home page of mvc web app
but I dont want that to be open when I open www.abc.com
I have one static page called index.htm should be open first
in mvc3 Global.asax code:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
How can I render to http://www.abc.com/mypage.html ?
what should I please help.
ashuthinks,
Based on your revised comments for the question. If you just want to show the 'Under contruction' type page with no links, then you can modify the web.config and add an app_offline.htm file. here's what those changes would look like:
web.config (bare bones):
<?xml version="1.0"?>
<configuration>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer>
</configuration>
app_offline.htm:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Your site title</title>
</head>
<body>
<div>
<span>Your Company name</span>
<h1>Sorry, server maintenance in progress </h1>
<h2>Please contact John Doe on 000 123 456789 for further information</h2>
</div>
</body>
</html>
when you need to put the site live, simply rename the above files to web.config_offline and app_offline.htm_offline and bring your 'normal' web.config into play. There are of course many ways to skin this cat but this has worked well with previous projects that I've worked on.
see:
http://weblogs.asp.net/scottgu/archive/2006/04/09/442332.aspx
for further details.

Resources