is an ajax call after rendering an mvc view duplication - asp.net-mvc-4

I'm going to be developing a new system and am toying with the idea of either creating a single page application or a full asp.net mvc website.
I want to utilise knockout so if I went down the mvc route i'd need to load my mvc view and on document ready then make the ajax call to bind to my knockout view model.
Is this a bad approach as i'm effectively making 2 calls to get one page?

Depends really on your exact page design and behavior.
But generally MVC and knockout do not require you to get the data via ajax, you can populate your data from the server then manually apply bindings to your observables.
saving the data could be done via ajax.
Of course its all theory now, you need to see your screen designs and check which way to go.

Related

Best way to post to a .Net Core Web API

I created a Web API with .Net Core.
I currently have the form from the .cshtml page posting through to a normal MVC controller and then using the HTTP Post method to post to the Web API endpoint.
Is it better to post directly from the form on the .cshtml to the WebApi endpoint?
I'm relatively new so not sure which is better.
Imho the current approach is correct: you post some data to a controller inside your application and then do stuff with this data (in this case sending them back to a Web API).
Why is correct? Because you can do all sort of checks inside the controller before sending any data to the Web API (like data validation, transformations, composition etc...). Also, I'm not sure if you can post directly to a Web API using Blazor methods for posts. To do that I think you have to write the form using plain HTML and than detect the submit event using Javascript, where you finally post the form data to the Web API. But again, I think the current approach is good (if not optimal)
it's not a bad solution by any means but if your API is publicly accessible (not just from your web project with the mvc controllers) I would suggest posting directly to the API.
Posting directly to the API reduces roundtrips. And also the validation and everything should be handled by the API.
Use Web APIs when you want to deal with data or HTTP status codes only, i.e. not expecting HTML to be returned. Typical use cases from a web perspective are doing any asynchronous communication through Javascript (native JS, Vue, Angular, React, JQuery, etc....)
If you expect HTML to be returned, use MVC or whatever view framework you want to use. In this case it is perfectly fine to call other APIs from the MVC controller.

Should I have views in a .NET Core API

At the company I work at we have a couple of different services
API (.NET Core)
Internal Frontend (React)
External Frontend for customers (React)
I was asked to create some views which will be converted to PDF's by an API, but I can't decide where to put them as they are not related to our Internal- or External-facing projects.
My first thought was to put them in our .NET Core API. However this has previously been a strict json-only API, so I have an itch that this is not the intended use.
So internet, my questions are as follows
Is it a big NO-NO to put Razor-views in our API?
Should I dedicate a microservice to this?
What is best practice?
Thanks in advance!
You're right, Razor views will be excess. I see two options:
Backend: Create an endpoint which will return a PDF file based on passed data. Of course you can expand data. This way is similar with Razor: you have a view model and render it to PDF file. An example of library: iTextSharp.LGPLv2.Core
Frontend: Convert HTML to PDF on client's side. Something like react-pdf
I prefer first option, because, first of all, there is already an option "Save as PDF" in browsers, so it will be some kind of duplication of functionality. And on the other hand back-end PDF generation seems more flexible (you can use all of your domain and you can create independent layout either) and you can organise some kind of file cache.

Mvc 4 single page application view navigation to different sections of site

I'm embarking in my first spa mvc 4 app and I've watched the Steve Sanderson talk which was great but his final delivery tracker app ends up with 3 views that are all declared in the same view page. This is fine for a small app but how do you manage this on a larger scale when you have different sections of the site that have different data. The site I want to build needs to remain on a single page because I want to keep a chat window open similar to the Facebook style chat and i am going to be using SignalR to push data to the client in fixed sections within the app. Do I just use the #Ajax.actions to load up completely different sections of my site much as I would if I was just creating a non spa site? The plan is to keep the user in a specific section of the I site for a majority of the time, but I will want settings pages and user profile management pages that are defined in separate views.
Any good sample code would be greatly appreciated I'm planning to just use the bog standard spa with knockout and nav.js unless someone can suggest a more mature spa technology for mvc/entity framework that's got some good documentation and is popular.
What I do is poor mans SPA, which is basically make my site like a standard ASP.NET MVC app so I have multiple views, multiple controllers and actions and I have a shell page with a container div which I use as the container for the whole site to load my views into with Ajax calls, so I have lots and lots of jQuery ajax calls, I've somewhat tried to refactor my client side JS and make a generic navigate to Javascript method (among other things) in my shell page, which I then invoke from the child views, so a click on a certain ActionLink in a particular child view and I would call my generic JS page loader:
GoToPage(controller, action, query)
which will use jQuery Ajax to lad the destination controller/action/view into the container div in shell.cshtml. For navigation I use Ben Alman's hashchange plugin to detect hash change events and load the appropriate views into my container div. There are obvious downsides to this approach as you're rally not building a real SPA, you're making a server side app with a SPA facade, and actually the performance difference between this and a proper spa which only gets data from the server (not HTML) is slightly noticeable, however if you're a traditional ASP.NET MVC developer this saves you from having to take up new libraries like Sammy.js and knockout etc. The biggest downside of this is that you'll be writing a lot of repetitive wiring javascript which can quickly become a tangled mess, especially if you have a lot of forms. Though you can take certain steps to re-factor and reuse common code. So in summary generating views server side and retrieving them with Ajax probably isn't the most optimal SPA solution, but for me it had the least learning curve (none actually lol). I've recently been looking at Durandal and I think it finally provides a very viable solution to creating SPAs, I specially like how unlike Sammy.js you don't have to load all views on the initial page load, even if the user isn't going to visit those pages. A nice getting started tutorial is provided here.

How to combine Web Api and MVC best in a single web app

I am about to create a simple web app and I am wondering if I should use ASP.NET MVC 4 new feature Web API.
What's the best way to do this ?
I've done some researches and I found out there are two option :
Option 1
Make the Web Api my service layer and call it from the controller to read/write data, and render the view using view models and razor.
Option 2
Make the Web Api my service layer and call it directly from the view using Javascript.
I am not a big fan of Option 2 since I feel like I am neglecting the controller which will be used only for redirection between pages. Besides I prefer using razor rather than Javascript.
And If I choose Option 1 will I have to make an instance of one Web API in the controller? because this feels like I am doing something wrong.
What's the best option ? Is there any other options I haven't considered ?
And if you can give some references or books which can help me, I would appreciate it.
Thanks.
I usually have another layer (which can be a different project/assembly depending on the size and complexity of your application) for my business rules. You can call this business services, or whatever works on your case.
So both MVC controllers and API controllers use this layer; which keeps the application dry.
I personally prefer to only keep complex operations in my business layers, which means if I need to read something from my persistence layer to display in my views, I do it directly on the MVC controller. This is a matter of personal preference but I prefer to go the CQRS way.
So you MVC controllers are going to instantiate these business services (or they will be injected into your controllers if you are using IoC). For read operations you can choose to go straight to your persistance layer or use another read strategy.
The same will happen to your API controllers, they will use this "common" layer of services.
You don't need to instantiate your API Controllers on your MVC Controllers.
Consuming your Web Api controllers via AJAX is ok if you are developing a SPA or similar.
There is no a single way to structure your application, there are just different ways and every one has more or less pain attached.
If you are considering introducing tests in your applications (and you should :)); then you should structure it in a way it is easy to test each part of it.
Just my 2 cents.
The whole point of Web API is to be a stateless RESTful service. There would never be an instance of it if you're doing it right. I realize this question is old and you may personally have learned this, but the answer isn't as much for you as it is an answer to a frequently-asked question.
Note that when speaking of Web API, more often than not, people are talking about ApiControllers and not basic MVC "Controllers" that take routes and turn them into Views.
So in your project, you may have some "Controllers" which do some basic view logic, but no business logic. Don't confuse that with your Service Layer which is a wrapper for your Business Logic and Persistence access.
I, and many, am of the opinion that ApiControllers shouldn't be mixed with your MVC application. Keep in mind that MVC does not mix well with Web API. As Filip W says:
Many of the concepts used by Web API and MVC, even though similar at
first glance, are actually not compatible. For example, Web API
attributes are System.Web.Http.Filters.Filter and MVC attributes are
System.Web.Mvc.Filter - and they are not interchangeable.
Most flexible answer
So what you do is create a subdomain named api.YourWebsite.com, and build a new Web API ApiController project there. That Web API Project should do NOTHING more than instantiate and expose Business Logic via ApiControllers and Dependency Injection.
Alternative 1
Service-Oriented Architecture is all about reusability. If you want to keep your applications DRY, you should definitely fall into SOA. Though, every situation is different. If you will never ever use the same business logic in this website in any other application (desktop, android, tablet, ewPhones, etc), then you have an alternative method.
Create your Busines Logic Layer as a different Project, and access it directly from your web app. When your Javascript (Angular/Razor?) Controllers make a call, they can call into your ViewModels and/or Codebehind or something similar, which can instantiate Business Logic and directly access it. No need for services if everything is right there and won't be reused.
Alternative 2
Go ahead and put your Web API ApiControllers in the same project. But, be sure you separate them into different folders from your MVC "Controllers." Still, when your Javascript Controllers make a call, they will be making Routing calls to your website for stateless returns. Do not mix the stateless ApiControllers with your ViewModels and other MVC code.
The downside to this is a lack of SOC. Now you have Service-Layer and UI-Layer mixed, and your UI-Layer is forced to access your Business Logic Layer (DLL). What's wrong with that if Alternative 1 did it?
Well, what's wrong is that Alternative 1 was a small application with no room for growth. Anything else (The original plan, or Alternative 2 here) should have UI's that have no clue whatsoever that Business Logic (or Persistence) even exist. They should go about their doodies unawares of the backend world.

MVC 4 ASP.NET 4.5 dynamic form builder options?

I have developed custom form builder type application using ASP.NET 3 years back. Now working on new project and it has similar requirement. I think there must be something new and easy to do same thing using MVC4 or ASP.NET 4.5 web forms. Any pointers?
Requirement in detail,
This is a web application
Authorised users login to web site and given the option to fill in the form
This form captures the information which then sent to third party
Third party keep reviewing their system and may ask for more details in future
My application needs modification to capture this extra(or say changing) information
Is there any way I can change only DB model to accommodate these extra fields and they will automatically appear on form without any code changes to UI or BL level?
I am not too sure what you are trying to accomplish but maybe this could help ?
http://lostechies.com/erichexter/2012/11/20/twitter-bootstrap-mvc4-the-template-nuget-package-for-asp-net-mvc4-projects/
Look at how they automatically generate the bootstrap views depending on which view model get's passed.