Reportviewer datasource in asp.net-mvc - asp.net-mvc

How do I integrate ReportViewer in asp.net MVC project?
I want to add business objects of MVCProject.Model namespace. ReportViewer allows Business objects of DataSet.
Is it possible to choose other data source, like LinqDataSource, or Direct object to LINQ-to-SQL class objects?
What would be the best solution to add reports in an MVC project?

An alternative way to do this would be to generate the report on the reporting server, then stream it to the mvc app as a PDF.

I got an idea that is not tested but may work.
1- Place report viewer control in a standard ASP.Net web form page (e.g. ReportViewer.aspx)
2- Under your MVC, add an iframe that references to this ReportViewer.aspx page
3- Pass parameters to the page using sessions or query strings
Let me know if th is works

It's gonna be tough. First, you need ViewState so you'll need to host the report in a regular WebForms page. This isn't too bad though - WebForms and MVC work fine side-by-side.
The hard part is binding to real IEnumerable objects and not those phoney-baloney ObjectDataSources.
The first step is to build up a report data model. You can do this in code, with queries, whatever, however you want. A structure something like this (but obviously much bigger) is typical:
public class ReportSource
{
public Floogle[] Floogles { get; set; }
}
public class Floogle
{
public Doodad[] Doodads { get; set; }
public string Text { get; set; }
}
public class Doodad
{
public int Number { get; set; }
}
The trick is to use a BindingSource control in your report and set the DataSource property to typeof(ReportSource) - yes, the data source is the type of your report model.
When designing your report you won't get a lot of richness, but you'll be able to do it.
As far as third party reporting solutions go, we've found Telerik's to be the best option.

I've got a small project I threw up on codeplex that is an mvc project with a report.
http://mvctaskmanagement.codeplex.com/
Basically since I do dev on an XP box, my web form had to get pushed to a separate project. Since I have a service layer proj, I stuck it in there.
From there I call my report via a ajax post shooting the params over to the report page, which then passes it down to the same service layer used to generate the preview.
Good luck!

Related

Dynamically change models and controllers after publishing website in ASP.NET Core MVC

I'm using ASP.NET Core MVC 2. I need to operator can change some elements of Models or view codes. How I can code or design for it.
For example: I have a "news" model and I want to operator (final user of website, who can't code or access to visual studio) can add this to "news" model:
public string ImageUrl { get; set; }
and also can change the database without coding.
Thanks
If you want to design a completely extensible model, you could use something called Entity–attribute–value model (EAV).
Your model might have a couple common attributes like Title and Summary. Then you might have a list of Custom Fields, the first of which could be ImageUrl. You could create your own class called CustomField or something similar, which would have properties such as FieldName, and DataType.
public string Title { get; set; }
public string Summary { get; set; }
public List<CustomField> CustomFields { get; set; }
You would then have a table full of custom field values and the tables they belong to. It gets pretty complex.
When you want to automatically reflect your model changes to the database, you will need an ORM framework like EF (Entity Framework). You can check more here.
In order for your case to happen is to build your own configuration platform that may use several tools and mechanincs that will allow you to generate code and then compile it. Such as T4 and more.
In general, this is a very hard task to accomplish and even big experienced teams would have troubles to build something similar.
I can not post any code, as this would only seem a desperate approach.

MVC Web form without database

I'm in the process of refitting a website that I'd previously built using ASP.net with VB in the code-behind, into MVC with VB so that it's more responsive to different screen sizes and device types.
So far I've been able to replicate six of the pages plus the Site.Master files. Now I'm turning my attention to the Contact page which in asp.net takes data from a form, validates it for completion and data-type compliance and then passes it to the code-behind which uses it to generate an email.
I've done quite a lot of reading which suggests using a Model but all the examples I've found then use that Model to populate or query a database using LINQ.
How can I do this without a database?
The M in MVC stands for Model, not Mdatabase. You can use whatever you want as the model. Most applications use a database and most .NET applications use EF to access a database (or at least Microsoft want it that way) but you can use whatever you want.
Using a database engine is recommended as permanent storage, but essentially you can create model class for contact page without involving a database like this:
public class Contact
{
[Required]
public String Name { get; set; }
[Required]
public String EmailAddress { get; set; }
}
And you can use LINQ/lambda expressions after wrapping your model class into a collection (e.g. List), as example:
var list = new List<Contact>();
list.Add(new Contact { ... }); // adding items to the list
// Lambda syntax
var name = list.Select(x => x.Name); // returns a value from the list
// LINQ syntax
var email = (from item in list
select item.EmailAddress);
Then you can convert the code-behind logic to a controller action method as ActionResult each for GET and POST request. Afterwards, Redirect, RedirectToAction or simply return View() after data submission can be used for page handling.
About responsive page design to work with different screen sizes and device types, MVC itself not designed to present responsive layouts by default. You need to alter some HTML & CSS-related attributes, as similar problem here:
How to make an MVC web application adjust to automatically fit different screen sizes
NB: Since your problem doesn't include any code, the provided codes are just examples as figure to what should be done.

ASP.Net MVC model translate language for display

I am working on multi-language enabled mvc application. I have a translation table in database, which I bring on application start and save it in application memory.
The database structure is {TextId, LanguageId, Translation}. TextId is assigned to each UI element (like label, validators, dropdown list text, etc.). There is an admin interface to manage the translation text.
I want to know what is a good way to show translated text on UI, and where is the best place to do the actual translation. I do not want to use the resource manager, since the database is being used in other Asp & Asp.Net webforms applications.
Here is the model (for example)
public class UserLoginModel
{
[Required(ErrorMessage="ER001")]
[Range(6,10,ErrorMessage="ER002")]
[Display(Description="TX001", Name="TX002")]
public string LoginId { get; set; }
[Required(ErrorMessage="ER003"), DataType(DataType.Password)]
public string Password { get; set; }
public bool RememberMe { get; set; }
}
Language Id will be in Session["LanguageId"], and TranslationText is in Application variable.
Models reside in separate project, hence there is not direct access to session, but I can use DI (don't know whether it is a good practice!)
Here are following things I was considering:
Write Html helper extension like #Html.TranslateText("TX001"). I started with this method, but soon realized that #Html.ValidationMessage accepts only one message, irrespective of multiple validator attributes on property. I cannot use EditorFor templates either.
Use javascript to replace text ids with appropriate messages
Use reflection on model and replace text ids for attributes.
I am leaning towards option 3, by extending ModelMetadataProvider, or writing action filter attribute, or in EditorForModel template.
I am very confused on how to proceed. I am still in process of learning MVC. Hence. I would like to ask experts on how to handle this problem in best possible way.
Thanks,

Why does the interaction between model, view and contoller look different?

Im new to ASP.NET MVC, trying to learn the basics.
Im now trying to learn the relationship between the model ,view and controller.
The interaction between these three looks different, why? (Look at the arrows)
Source 1: MSDN
Source 2 (Page 65): Steven Sanderson
I would be glad if you help me sort out my confusion
Thanks
Edit:
What you are saying is that mvc can be implemented differently?
(Still asking about asp.net mvc - Not mvc in general)
I have been looking at the mvcmusicstore
and it looks like this.
Controller:
public ActionResult Details(int id)
{
var album = storeDB.Albums.Find(id);
return View(album);
}
Model:
public class Album
{
public int AlbumId { get; set; }
public int GenreId { get; set; }
public int ArtistId { get; set; }
public string Title { get; set; }
public decimal Price { get; set; }
public string AlbumArtUrl { get; set; }
public Genre Genre { get; set; }
public Artist Artist { get; set; }
}
view:
(Had to add as image, add code the normal way did not work)
This looks like the MSDN version, how would this be rewritten to fit Sandersons diagram?
Maybe this will help me understand!
Edit again:
Hi again
Let me sum this up. Please respond if I'm wrong.
The way Microsoft intended us to use mvc is the one we see in the above MSDN link and in MusicStore.
Then there are other "versions" of mvc such as Sandersons (or whereever it originates from).
So Microsoft give us a basic way of how to use the mvc framework, but it is ok to do it other ways.
A newbie should not get stressed by seeing different versions, sticking to the one seen in MSDN/MusicStore is perfectly fine.
The key difference is the inclusion of the "Presentation Model" in Sanderson's diagram. The ASP.NET MVC implementation often uses the Model as the Presentation Model, even though they can be different (and I would argue that they should be different, but it's a holy war and there's no need to get into that).
In most very simple ASP.NET MVC applications, the model is the data entity. Whether it's an EF entity or a Linq2Sql entity, makes no difference. This is because most applications are simple forms-over-data and the presentation is probably one-to-one with the persistence.
The MVC pattern itself, however, doesn't require this. In a more pure framework-agnostic form, Sanderson's diagram illustrates the fact that the controller is interacting with the model. The model is really the "gateway to the domain core" in this sense. Controllers and views are part of the application, but the model has the underlying business logic and, beneath that, layers of persistence and other infrastructure information (properly separated, of course) which are unknown to the application. The boundary between the controller and the model is the application boundary, the point at which other applications can also connect to the domain core and interact with it.
A presentation model is usually nothing more than a simple value object. It's not an entity of any kind in the sense that it doesn't have to exhibit any business behavior or maintain its lifecycle the way that a persistable business entity would. It's just a flat object with some attributes of data.
It can have some behavior, but that behavior is for the application and not for the domain core. For example, maybe it has some methods or properties that the view can use. The presentation model is part of the application, so it's presentation-layer-aware. Essentially it just holds data that the controller needs to pass to the view (or even receive from the request, depending on the framework).
In ASP.NET MVC you'll very often see the model used also as the presentation model. The same object may be playing two roles in those cases, but the two roles are definitely different.
Edit: Just noticed your updated question...
In that example, Album is playing the role of both domain model and presentation model. (In fact, I would argue that it's not a domain model at all because it's too anemic. Notice that it has no functionality, just bare data.) In a richer domain model, Album would likely have more functionality. For a contrived example, imagine that instead of auto-implemented properties it has properties which enforce business logic when set, and it has methods on it such as AddSong(Song song) and Play() and other such behaviors.
This richer model can still be used as a presentation model, but the functionality might not make sense in the scope of a view. A view is really suited more toward just bare data elements. The controller would interact with the model's functionality. So you might create a presentation model similar to the Album domain model in structure, and it would look just like the one in your example.
Going forward, what if the view needs other data as well? Maybe the view needs to know something about other models which aren't part of the same aggregate as Album. It wouldn't make sense to modify the domain models to accommodate the view. That's backwards. The presentation should wrap around the domain core, not the other way around. So you might add properties to the presentation model which are populated from other things inside the controller.
So you might end up with something like this...
Domain model:
public class Album
{
public int ID { get; private set; } // might need to be immutable
private string _title;
public string Title
{
get { return _title; }
set
{
// don't allow empty titles
if (string.IsNullOrWhiteSpace(value))
throw new ArgumentNullException("Title");
_title = value;
}
}
private Album() { }
public Album(int id, string title)
{
ID = id;
Title = title;
}
public void Play()
{
// some implementation
}
public void SomeOtherMethod()
{
// some implementation
}
}
As the business domain grows and changes, this model could change with it. The main point is that it changes at the behest of the domain core and the business logic, not at the behest of UI implementations.
A particular "page" on a particular website which uses this domain core may need specific information about an album, and maybe some other information as well. You'd tailor a presentation model to fit that:
public class AlbumViewModel
{
public int ID { get; set; }
public string Title { get; set; }
public string Owner { get; set; }
public IEnumerable<Listener> Listeners { get; set; }
public string SomeCompletelyUnrelatedValueNeededByTheView { get; set; }
}
The controller would then construct this presentation model for the view:
public ActionResult Details(int id)
{
// TODO: validate and sanitize any inputs
var album = AlbumRepository.Get(id); // after all, why bind the UI _directly_ to the DB? that's just silly
var someOtherObject = SomeOtherRepository.Get(someOtherValueFromSomewhereElse);
var albumVM = new AlbumViewModel
{
ID = album.ID,
Title = album.Title,
Owner = somethingElse.SomeValue,
Listeners = someOtherObject.GetListeners(album),
SomeCompletelyUnrelatedValueNeededByTheView = "foo"
};
return View(albumVM);
}
This is a much more manual approach overall. It's useful when you have more complex domain models, multiple complex applications interacting with that domain, different technology stacks throughout the domain, etc. For simple forms-over-data applications the standard ASP.NET MVC implementation usually works fine. Most of the tutorials for it reflect this, consolidating multiple responsibilities into fewer objects, using decorators instead of explicit code (assuming the use of the same stack of tools across the board), etc.
The examples you're looking at get you to a working application very quickly with very little code. As with any framework, it works beautifully if you do things the way the framework intends you to do them. If you need to step outside the bounds of the framework, you can still maintain the pattern in a more abstract and framework-agnostic way.
Edit: For your update again...
In a way, yes. ASP.NET MVC is a framework which borrows a lot from the MVC pattern in general. As with all things, there's more than one way to do it. Sticking with simple implementations and quick applications, the functionality provided by the ASP.NET MVC framework and explained in its various tutorials is perfectly acceptable and is a great example of the use of a framework... Using a tool to get a job done.
They stick to the pattern in all the most meaningful ways. At the same time, however, in the true nature of a framework (which is generally outside the scope of a pattern description), they try to give you tools which make very light work of the actual development. If you don't have a pressing need to separate your domain models from your presentation models, you don't have to. One model can play both roles. If you don't have a pressing need to abstract your data access behind, say, a repository pattern, you don't have to. You can throw together some quick Entity Framework functionality directly in your Models and be done with it.
Ultimately it's up to the needs of the project, the preferences of the developer(s), and so on. The patterns are more academic, the frameworks are more pragmatic. Balancing the two is the key.
I guess the distinction is that in asp.net MVC you can have strongly typed views which have 'knowledge' of your model and the entity being passed through to the view. In its purest sense though the View shouldn't (or rather, neednt) have any knowledge of the model. For that reason I say Steven Sandersons example is better.
Fantastic book by he way!
I wouldn't sweat it - Stephen Sanderson's diagram is showing less of the cycle but in more detail.
I'd interpret the MS article arrows as:
Controller populates model (from services, etc)
Controller directs to view
View populates through binding model
The microsoft diagram isn't really that useful or informative or useful though in my opinion. You could equally argue that arrows could go in different directions - or even in both directions like Sanderson's do. E.g. Controller also received models from binding, etc.
The Sanderson arrows are annotated well and are self-explicit, and the book is great.

Best way for creating reports in ASP.NET MVC

After building my application in ASP.NET MVC and MS sql server, I would now like to display some statistics regarding my data.
What would be the easiest way to create HTML reports which are built of data crossing several tables? (Once the fields are picked they'll be static, meanning a single view is required)
I though their ought to be something in the lines of a wizard letting you drag fields from your tables to a form and generates the logic behind...
I wrote a blog post about this in September. It's a way to render a PDF content type using an RPT file in the application. It covers everything except the creation of the RDLC file, including how to write unit tests for the controller.
Microsoft Reporting Services?
"I though their ought to be something in the lines of a wizard letting you drag fields from your tables to a form and generates the logic behind..." - this is the basic idea behind ASP.NET WebForms. But, please do not abandon MVC in favour of WebForms.
One way to achieve what you want is to create a class representing your stats, e.g.
public class Statistic
{
public string TableName { get; set; }
public int RowCount { get; set; }
}
Your Model code could populate an IList<Statistic> instance which is passed to your View, which renders the stats accordingly.
You could take a look at Dynamic Data .... http://www.asp.net/dynamicdata

Resources