Saturday, February 11, 2017

Using MVC views within Angular 2!

Assuming this application and this incorporation into MVC, one may obviously change up starting-point.component.ts like so to have a template in the form of an .html file, in this case starting-point.template.html sitting in the same folder as starting-point.component.

import { Component, Input } from '@angular/core';
import {Http, Headers} from '@angular/http';
import {Observable} from 'rxjs/observable';
@Component({
   selector: 'entry-point',
   templateUrl: '/Whatever/app/components/starting-point.template.html',
   providers: []
})
export class StartingPoint {}

 
 

Similarly, a change up like so...

import { Component, Input } from '@angular/core';
import {Http, Headers} from '@angular/http';
import {Observable} from 'rxjs/observable';
@Component({
   selector: 'entry-point',
   templateUrl: '/Partial/SomethingErOther',
   providers: []
})
export class StartingPoint {}

 
 

...is going to give you back the view from a controller action assuming a controller like so:

using System.Web.Mvc;
namespace MyApp.Controllers
{
   public class PartialController : Controller
   {
      public ActionResult SomethingErOther() => PartialView();
   }
}

 
 

Inside of the view, a .cshtml file at /Views/Partial/SomethingErOther.cshtml, you may use the familiar Razor markup. I had some heartache in trying to put something in the ViewBag and then pull it out again in the view that the Angular stuff uses. If I set something in HomeController or WhateverController it cannot be surfaced in the view. I guess it just reads as null. If I set the same property in the PartialController's action like so...

using System.Web.Mvc;
namespace MpApp.Controllers
{
   public class PartialController : Controller
   {
      public ActionResult SomethingErOther()
      {
         ViewBag.Message = "huh?";
         return PartialView();
      }
   }
}

 
 

...well, that works but also clobbers the same ViewBag setting back in the regular context of HomeController and WhateverController and views associated with them, making it behave nullesque therein. This is strange behavior, but it is also not the end of the world. If you just see this divide you should be able to tiptoe around it and get what you need working.

No comments:

Post a Comment