JSON Data to View Via C# Razor - c#

I just learned that you can pass raw json data to the view via c# razor. Something like:
#Html.Raw(Json.Encode(Model.SomeData))
I was wondering about the pros and cons of sending data to the view this way compared to retrieving the data through a web service call.
So far all I know is that the data I pass to the view must be displayed inline on the web page. So I guess the big things I would like to know overall is:
1) How safe is this as a method of retrieving data for an app?
2) Is there anything I can do if I wanted to pass possibly sensitive information to the view this way (like encrypt the data on the server and decrypt on the view)
3) When in general is the best time to do something like this

Html.Raw is a helper method which simply renders some raw text in your view. That text can be HTML, JSON amongst other things.
I was wondering about the pros and cons of sending data to the view this way compared to retrieving the data through a web service call.
This embeds the the data as text in your view. You would need to get your view again (or a partial view) if you want that data. This is also tied to a view engine (Razor in this case). This is not a replacement for web services. See answer to item 3 below for more.
1) How safe is this as a method of retrieving data for an app?
Whether you use a web service or this technique, if your data is sensitive then you should use HTTPS or encrypt it or some other technique.
It is as safe as you make it.
2) Is there anything I can do if I wanted to pass possibly sensitive information to the view this way (like encrypt the data on the server and decrypt on the view)
See answer to item 1 above.
3) When in general is the best time to do something like this
I would find it very odd if you did this in your web service because then your web service will be tied to a view engine.
I have done this in the past when I wanted to include some data in my view. For example, I would include some data like this and on the browser side (using KnockoutJs) I would create a ViewModel out of this. So basically if you want some JSON to be included with your view, you can use this technique.

Related

Common approach of sending sensitive data between pages asp.net core

I went through many articles regarding sending data between pages in asp.net core. Most of the issues are old or listing the mechanisms for retaining data "Hidden form fields, query-string, Temp data, sessions" in a general way, I need to understand when to use them and in which situation.
In my situation, I have a list of records page and links to each record details page. The common approach here in ASP.NET Core to asp-route-{value} in the anchor tag which will send the data as query parameters but the ID to be sent to another page is sensitive so I need to hide it from the user. My question here is there any built-in asp.net core mechanism for this situation .. I don't want to build other solutions like encrypting the data or whatever if there is a common approach for sending the data with GET Request.
Another point that caught my attention, I read in one of the articles that in the Post case is not preferable to send hidden fields for sensitive data, so what is the approach as well for the POST method.

MVC Refreshing DataTables Data

I am using data tables along with MVC.
What I'm trying to achieve is updating the data inside a DataTable on 5 second interval, without refreshing the whole page, but I'm having trouble with the logic behind it.
At the moment I can populate the DataTable using my model or by using data returned in JSON format. But I seem to have problems with both.
Model Approach
JQuery calls a controller which returns a partial view which contains the whole table which has been populated. This works and is quite straight forward.
However it seems unnecessary to return the HTML every call, and since the table is being pulled in from a partial view, and each time page numbers and other settings are lost.
JSON Approach
JQuery calls a controller which returns the data we need in JSON format, this allows the relevant parts of the page to be updated.
However I don't see a way to update the data once it has been set, Apart from using DataTables built in AJAX call, which doesn't seem to allow for polling.
Any thoughts on whether these are good or bad approaches would be helpful.
Thanks,
If the data source is MSSQL, then you could look at using SignalR and SQLDependency as per this example https://www.codeproject.com/Articles/874240/SignalR-Database-update-notifications-in-ASP-NET-M

Adding form fields dynamically, then saving them away

I have an asp.net form page used for capturing data for a particular task, the task items will be displayed in a tabular fashion.
there may be a number of items included in this task, for which I wish to add the appropriate form fields dynamically.
I then will need to 'save' the data from the form.
I was wondering what would be the easiest way to approach this.
I had planned on generating a single 'starter' row and then using jQuery to clone it (whilst renaming the inputs slightly) as I needed.
only problem with this is that depending on the types of task items, the form fields would be slightly different. which would mean having a very complex 'starter' row to start with and a fair bit of code in the js along with the cloning - or I guess holding each 'type' of starter rown, hidden somewhere on the page and cloning them into life as necessary
or maybe having a js function for each task type that uses append(...html...)
I was trying to avoid using an updatepanel - in which I could generate all the new fields in the code behind, but maybe that would be simpler?
but along with this, when I actually want to save the data away, presume the only way to get at it all is to use the Request.Form collection?
interested in how you guys would approach this, as trying to not make this hard on myself.
thanks
nat
If you are building the UI using JQuery, why not send the final results back to the server via a web service, called by a JQuery $.ajax command? This way, you wouldn't need to rebuild the UI from client-side code after every postback, which would be the problem with building content client-side, but posting back from every response.
It looks like your form is very dynamic in nature. Creating all these dynamic controls on the server side can become really messy, especially because you have to work with it both on the server and on the client.
An alternative would be to do everything html related on the client and leave only the data processing to the server, using json as the data format.
I just started to work with angular and I am really impressed.

Using Existing Web Service within MVC 3

FYI, I'm working on my first MVC web application using MVC 3 and Razor with C#, and .NET3.5/4.0, and I'm looking for the "best pratice" approach for using existing web services in an MVC 3 application. From what I have figured out so far it looks like all I need to do is the following. Include a reference to the existing web service in the MVC project, create a Model for the data I desire to use in the application, create a Controller that makes the web service call that then fills an object created from the Model (reading about AutoMapper to see how this helps in that process), and then create a View to display the data that was translated into the MVC view model.
The part that I'm having questions about is what is the best way to retrieve and create/update the data from the web service. Maybe I'm over complicating this but it seems like I'm missing something.
Do I need to create a "Domain Model" that maps to the data retrieved from the web service and then create "View Models" that map to the domain model, and then use the View Models within the MVC 3 application?
Basically I'm looking for input on how best to use existing web services as my data access layer.
On your data access layer you would open the connection, get the raw data and then close it. Identically to how you would get data from your database. You would then convert this raw data to your business layer (domain model) via a data adapter. Then any top level applications, such as your MVC3 website, will convert this domain model into an approriate view model, along with any other data for rendering, again through a data adapter.
The main argument for doing it this way is that the service is now accessible to any top tier application that requires it. It is also makes logical sense to put any sort of data retrieval methods in your data access layer, since that's logically what the data access layer is designed to do.
There is always the temptation to simply access the service from your controller, but separation of concerns might suggest this is a bad way to structure your code. You should encapsulate the service as a domain/business layer service for your applications.
So in short, you don't need to, but best practice suggests you should. It can feel tedious sometimes when there is little or no conversion between layers, but it often helps to stay consistent.
To obey the MVC pattern and its separation of concerns, calling the database must be in the model. And if this web services calls the database somehow, it should be at the Model level.
let the UI talk to the model directly, in case later u needed a webservice to integrate with another system you can create a service which calls that model
And you may want to cache it if its read-only

Rewriting a legacy-proprietary Web Application to MVC3/Entity-Code-First

I've posted a few questions over the months about structure of ASP.NET applications and Database-Abstraction-Layers, for the purposes of rewriting (from the ground-up), a legacy web application. I've recently stumbled on MVC3/Entity-Code-First and after spending some time with it, have fallen in love with how it works, how things are abstracted out, and I'm looking for any excuse to use it!
The legacy application is a C++/CLI windows service that generates it's own HTML (very old-school HTML at that with CSS just used for colours, and tables-abound), and with interface very tightly coupled to business-logic. Basically, anything is going to be an improvement.
However, and perhaps this is because I have not spent enough time yet with MVC, I have a few nagging doubts and wondered if some of you MVC-Pros could waft their experience in my direction.
The legacy app uses custom controls (it's own form of them) to bind combo-boxes to data, and dynamically repopulate dependent combo-boxes based on selections in another. In ASP.NET, this question is answered easily as one just throws an asp:DataList control on the page, binds it to a data source and voila. A bit of simple code allows you to then filter other combo boxes on the selected value. It also would be easy in ASP.NET, to implement another data-list that even automated dependent data in this fashion (which would mimic the behavior of the legacy app quite nicely). I can't seem to find a notion of custom controls in MVC, though I assume this kind of stuff is handled by jQuery calls to get data and throw it in to a combo box. But is this done for every combo-box on every page that has one? Is this a case for partial views with appropriate parameters being passed, or this just stupid?
I guess this relates more to the Entity Framework than MVC, but most of the examples I've found on the web, and tutorials, perform LINQ queries to return a collection of objects to display, e.g this, from the MvcMovie example:
public ActionResult Index()
{
var movies = from m in db.Movies
where m.ReleaseDate > new DateTime(1984, 6, 1)
select m;
return View(movies.ToList());
}
Which is then rendered using a #foreach loop in the view. This is all great. The legacy application has a single browse page that is used by all the other areas of the system (there are over 50). It does this by inspecting the column order defined for the user logged on, flattening any foreign keys (so that the field on the foreign table is displayed as opposed to the non-user-friendly primary key value) and also allows the user to apply custom filters to any column. It does this also for tables that have upward of 100k rows. How would one go about writing something similar using the Entity-framework and views? In ASP.NET I'd probably solve this by dynamically generating a grid view of some sort and have it auto-generate the columns and apply the filters. This seems like it might me more work in MVC. I am missing something?
The legacy application has several operations that operate over large sets of data. Now because it was a service, it could launch these threads without worrying about being shut-down. One of my questions here on SO was about static managers being around and the introduction of an AppPool recycle, but I have decided that having an auxiliary service is a good option. That said, the legacy app applies an update statement to large groups of records rather than single rows. Is this possible with Entity-Framework without writing custom SQL against the database that bypasses the normal models? I hope I don't have to do something like this (not that I would, this is just for example)
var records = from rec in myTable
where someField = someValue
select rec;
foreach(rec in records)
rec.applyCalculation();
db.SaveDbChanges();
I suspect this could take a lot of time, whereas the legacy app would just do:
UPDATE myTable
SET field1 = calc
WHERE someField = someValue
So it's not entirely clear to me how we use our models in this manner.
The legacy application has some data panels in the layout that get carried around whatever page you're on. Looking here on Stackoverflow, I found this question, which implies that every view needs to pass this information to the layout? Is this so, or is there a better way? Ideally, I'd like my layout to be able to access a particular model/repository and display the data in a side-panel. Adding to every view page could be quite repetitive and prone to error. Not to mention the time it would take if I needed to modify something. A partial view would do here, but again I am unsure how to pass a model to it on the layout page.
Finally, I was disappointed, after installing Ef-Code-First, to find that a really nice attribute, SourceName has not made it in, yet. This would be very nice in mapping against legacy tables/columns and I am not entirely sure why it has been left out at this point (at least, my intellisense says it's not there!) Has anyone got an idea when this might come about? I could do without it for a while, but ultimately it would be incredibly useful.
Sorry for the lengthy questions. After ages of investigative work in ASP.NET and MVC3, I really want to go with MVC3!
If I managed to extract the questions correctly then this would be my reply:
You are right in your thinking about master - detail dropdowns (or other controls, for that matter). jQuery AJAX/JSON calls (mostly GETs) will be what you need. If you only have one dropdown on your page, then of course you don't need that kind of interactivity - you can just prepare the model for it in your controller action (you create a SelectList object).
Here you would most likely end up using some kind of a grid system like jqGrid or Flexigrid. They do most of the stuff regarding filtering/searching/querying themselves. Still you will have to provide JSON controller actions that will be serving data.
Yes you can execute SQL via EF. There's ExecuteStoreQuery() and ExecuteStoreCommand(). Here's more on those http://msdn.microsoft.com/en-us/library/ee358769.aspx
You can call RenderAction() from the view and have this action prepare the data on demand (whenever you call it) and render out the Partial (or normal) view and feed the data (model) to it. RenderPartial() is a bit more clumsy with this - it requires you to have the model already available in the view in which you are calling RenderPartial(). RenderPartial() never goes back to the controller action - it just renders out that HTML defined in the template using the model you provided in its call from within the view.
Unfortunately I don't know the answer to this.
HTH
You might not like it, but it could make a lot more sense to just refactor the c++ application. Especially to the business. There's nothing wrong with generating html. Much easier to refactor to modern html/css than a set of templates.

Categories