AngularJS Accessing C# MVC Index return Object - c#

Morning all,
When I do use angularjs to do a http.get I can store the result
var response = $http.get("somethingUseful")
However, when angularjs handles the routing of the url (specifically the index page)
I've got:
Controller.cs:
public ActionResult Index (){
return View(new FunkyModel())
}
within
Index.cshtml:
#model FunkyModel
can access Model etc..., happy days!
though in
Template.html
what's the easiest way to then access this without doing a JSON.Encode or without having to make a second request?
Thanks in advance!

To be honest - it is not the proper way of using Angular + MVC. You shouldn't expect to share models between back-end and front-end code.
You should use JsonResult and send all the data to the view and let Angular load a view for you. In case it is not possible, another request for necessary data is a viable option(not ideal though).
In my opinion building MVC application with Angular on a front-end is a misunderstanding of concepts behind this technologies. Angular is the best when is used as a engine for SPA(Single Page Application), where you can use its routing features, views loading and many many more.

Related

MVC for a single page? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am not well-versed with MVC, although I have been reading up on plenty of its materials for the past days. Now, I need to make a web project that uses only one web page. The web page will display data from an existing database, as well as add and edit entries. I was told to use MVC. Although in my study, it appears to me that MVC is more appropriate for larger projects. How do I go about using MVC for my single-paged project? I was thinking something like dbcontext -> repository -> controllers -> models -> views. Would that be correct, or is there a more efficient way to do it?
If I were to not use MVC, what can I use?
EDIT: What would be the best approach in using MVC on a project with one page?
Yes You could. There are numerous approaches to this kind of task, I will name two of them.
MVC Approach
The MVC approach is as follows:
You will have one controller that will contain all your input logic and action results.
For example:
public class HomeController : Controller
{
public ActionResult index()
{
return view();
}
public ActionResult ContactUs()
{
return view();
}
public ActionResult About()
{
return view();
}
}
Then you create a layout page and a view (or Partial view) For each action, then you route in the same controller, this way creating a single web page that is only changing content inside the layout.
The Pros:
You contain all your logic inside one controller, thus create and easy to access code, as you know where all your input logic is.
You can use razor to control your views through your models, allowing you to create custom controls designed for your needs and properties, making it easy to connect with your server for get/post requests.
The Cons
Your controller can grow bigger as the website grows, thus creating a code that is "hard-to-maintain". The more pages you add, the more logic will be added to the home controller making the code in the controller long, unreadable and very hard to maintain easily.
Angular Approach:
The angular approach states, that you will have one action in the controller for beginning - index (aka home page):
public class HomeController : Controller
{
public ActionResult index()
{
return view();
}
}
You will then create a layout page and html pages to render inside it and then make your navigation with angular ui-router.
for example:
var myApp = angular.module('myApp', ["ngRoute"])
.config(function ($routeProvider) {
var baseUrl = $("base").first().attr("href");
$routeProvider.when('/',
{
templateUrl: baseUrl + 'Html/Home.html',
controller: 'myHomeCointroller'
});
$routeProvider.when('/About',
{
templateUrl: baseUrl + 'Html/About.html',
controller: 'myAboutController'
});
this way, you can make your navigation with angular 'location' dependency for example:
$location.path('/About');
Creating a layout page and a very easy to navigate system on this one layout page.
The layout page will only change it's content according to each html content.
The Pros
You create a very flexible and easy to maintain application, that will not consume alot of input logic (controller code) and will be angular controller driven, thus creating a very easy way to fix your code in the future as well.
The Cons
You cannot use razor in html pages, thus will have to create alot of ajax calls to your server, which will probably require you to write a web api or WCF to connect with your server in order to get/post data.
Your logic will spread in numerous angular controllers instead of one place (for example, all logic in Home Controller), this might take time when dealing with little problems that need attention.
It is your choice to decide which approach to take regarding the MVC.
There are alot of ways to do this with other frameworks but then again, it will never end.
Focus on your task as they told you, learn the principle of each approach that I told you and good luck on your way.
Material to read about views:
Views and partial views in MVC
Material to read about angular ui-router:
Angular routing explanation
If you need only one page application, you can use SPA template for ASP.NET Core: Building Single Page Applications on ASP.NET Core with JavaScriptServices.
They include are MVC ASP.NET + front-end MVVM frameworks like: Angular, Aurelia, Knockout or React.
Other option: use Razor pages for ASP.NET Core: Introduction to Razor Pages in ASP.NET Core:
Razor Pages is a new feature of ASP.NET Core MVC that makes coding
page-focused scenarios easier and more productive.

Umbraco and MVC and JSON

So I got pulled into a deep end having zero experience in umbraco and a tight deadline.
I don't know how umbraco works and how you integrate your MVC site into it really. A lot of headfuzz to get around.
basically the person I am inheriting it from created a basic controller from MVC and we can call the MVC site as we normally do.
I can also do JSON calls to the controller action which gives us back some data in a ViewModel. Great.
But when you browse to the site using umbraco and navigate to that same page, we run into big problems such as not being able to invoke the JSON call to get the data as it says object not found (in other words, the controller action is not found).
I read about umbraco basically overriding the default MVC routings but... why such a mess? :)
how can I integrate an existing MVC site into umbraco without much pain?
what is the url to call a controller action in umbraco integration?
say we have this:
public JsonResult GetPersonDetail(int id)
{
var vm = new AjaxPersonDetailViewModel(....);
return new JsonResult( Data = vm };
}
I can call this in JQuery like so:
/MyController/GetPersonDetail/1
so how do I do that with Umbraco?
Also try using this scaffolding package as well to get the initial bits for your controller in the right place http://our.umbraco.org/Documentation/Reference/Mvc/scaffolding.
Yes you can just manually create the files that the scaffolding process creates and reference them accordingly however i prefer to use that first then add/tweak the auto files to match what i need

WCF as MVC controller. model and views?

I've been searching on the net for possible answer to my question, but no luck at all.
I just wonder if I could use WCF as my Controller in ASP.NET MVC.
So if I call
(WCF)
http://localhost:1621/WCF/LogOut.svc?id=10001
It will work like
(MVC)
http://localhost:1621/WCF/LogOut?id=10001
Or I'm just having wrong thought about it?
Can you give some source for deeper knowledge in MVC and WCF.. Thanks!
The MVC states that the controller picks up requests and it is responsible for preparing the model and passing it to a view which is ultimately rendered.
Although from the perspective of web requests, WCF could possibly look like MVC, there is no easy way to make WCF render the HTML to the browser. This means that if WCF can implement "controllers" which produce "models" but is not designed to create "views".
However, if your web application can pick up XML/JSON data produced by WCF calls (i.e. you have your views implemented purely at the client side) then yes, WCF does a good job as a provider of the "controller/model" part of the MVC.

ASP.NET MVC: How to pass Dictionary<string, string> from controller to jquery for use?

As I am quite green for ASP.NET MVC so maybe my question is very simple for many experienced users.
I am now implementing a web-based platform and I am trying to pass some data in Dictionary from Controller to View using ViewBag.
However, I am not able to use those ViewBag in jQuery,
when I "alert" them, they become a series of [Object, Object].
So I would like to ask how I can retrieve those data in jQuery?
Thanks.
You can serialize a .NET dictionary to Json. The Json.NET library has first class support for this
just do a loop to go through dictionary in your view to bind to your controls. However, try to limit your business logic in views and keep in controller .
Or I am misunderstanding your question. Any specific example would help.
You could use jQuery Ajax to get this data from an action that returns the data in a JsonResult. While the other two approaches should work this approach does not require to load the whole bunch of data with the page and make your UI more responsive through Ajax.

Workflows in ASP.NET MVC

As a learning exercise, I want to migrate an existing flash application to ASP.NET MVC. It has around 20 forms, and although it's mostly linear, there is some degree of alternate flows based on user decisions or data returned.
Could anyone point me in the right direction of how a controller would handle this? I don't want my views to have to figure out where they go to next.
Update
I think I may not be understanding the correct way of building this. I saw each controller as taking care of a different section of the app, and having a main controller being responsible for workflow.
If this is not the approach I should be taking, what is the best way of doing this?
Update 2
Would Areas in ASP.NET MVC 2 take care of this sectioning of the app? I really don't like the idea of having too many actions in one controller...
In general:
Controllers are usually a collection of actions that deal with a logically coherent chunk of the application ( hence why you often see UserController / OrderController etc etc ).
MVC applications should be built using PRG ( post - redirect - get ) which means you will have 2 actions for each form, one that will display the form and the second, with the same name but decorated with [AcceptPost], that will process the form and redirect the user to the appropriate location based on the result.
The simplest way to learn how this works and migrate your app over is model each form as a simple dto with no logic, build a view for each form and 2 actions.
Once you have the logic working in the controller, you may want to migrate it out into some form of service that can be injected into the controller.
Specifically for your workflows:
Each workflow should probably have it's own controller. It may be useful to model them using some form of state pattern ( depending on the complexity of the workflow ), and providing a result from each state transition that your controller can translate into a redirect to the next step in the workflow.
When a form posts to a controller action it is the controller action to decide what to do with the posted results and which view to render next or redirect:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult HandleFormSubmission(FormCollection col)
{
// do something with posted data
// redirect to /someOtherController/someOtherAction
// which could show some other form
return RedirectToAction("someOtherAction", "someOtherController");
}
I was struggling with the same problem (using Windows Workflow Foundation with ASP.NET MVC) and I blogged about it here
Maybe you'll find it helpful, sorry for pushing my own link

Categories