As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I know a bunch of people that are really enjoying the improvements that ASP.NET MVC 2 made over the first release. I have just started to migrate our MVC 1 project over and so far areas has totally cleaned up the subfolder mess we had in our large scale application. As I dive deeper into all the improvements and changes that were made I still keep thinking to myself man it would be nice if they had x in this release. For instance, I would love it if they had some sort of dependency injection built in instead of having to use third party solutions.
My real question is now that ASP.NET MVC 2 is out in the wild, what features do want/wish the team had implemented and hope they will implement for ASP.NET MVC 3?
EDIT
Looks like dependency injection is built in for the first preview release of ASP.NET MVC 3! I like the features added so far. ASP.NET 3 preview one is out!
I think MVC 3 will not be too dramatic with it's improvements, but more steady and gradual.
The ASP.NET MVC 3 Roadmap has a snapshot of what the team are apparently looking at implementing in the next release and some of the points are very interesting.
I think my favourites from that list would probably be:
More AJAX Helpers: This'll bring the framework more in line with the Webforms world which has all these helpers already and to some degree, acts as a barrier to some people taking up the platform.
More Dependency Injection stuff - for those that want it, this is great. :)
Improved Caching support is the big win for me. Having that built right into the framework would be a great benefit and could result in some nice performance savings.
Additional ValidationAttributes wouldn't go a miss either. While the facility is great to add them, a good library of the common ones, such as Email and PropertiesMustMatch and so on.
I would like the complete removal of all magic strings.
I really wish they'd add the following:
Spark-style conditionals and loops using html tag attributes.
Updated: Visible project property to toggle compile-time validation of views.
Something to verify/validate that my routes are correct.
Membership provider solution that uses int instead of Guid for identification and allows mapping profile fields to a custom table rather than the generic but slow default.
Lambda-based helpers to avoid magic strings (currently in MvcFutures)
T4MVC template to auto-generate strongly typed helpers
Project wizards or templates to get a template that is already setup for IoC and similar concerns, preferably with a selection dialog to choose which framework to use for IoC, unit testing, etc.
Additional attributes (both filters and validation).
Hmmm, that's all I can think of right now :)
Tooling (T4 templates) to create Moq objects for unit testing would be very cool. Testing for certain objects in the framework is unnecessarily complicated, and having the ability to code-gen some of this would be very beneficial.
I would like:
Tooling
An alternative listing view using ajax e.g. using jqGrid (implementing sorting, pagination, search)
Enhancements to CRUD Pages detect entities relationships for entity framework classes, and to use another set of components based in fields type e.g. just as Dynamic Data does : )
As ASP.net MVC 3 will be .net 4 only, I'd like to see some stuff around asynchronous controllers and all the other new async/multithreading functions that .net 4 brings.
I'd like to see built-in support for things like IronRuby
MEF support would be nice.
I'd like to see a new way of handling routing, to make it easier to developer REST services. Currently I have routes like this:
context.MapRoute(null,
"api/posts",
new { controller = "Post", action = "Get" },
new { httpConstraint = new HttpMethodConstraint("GET") });
context.MapRoute(null,
"api/posts",
new { controller = "Post", action = "Insert" },
new { httpConstraint = new HttpMethodConstraint("POST") });
context.MapRoute(null,
"api/posts/{id}",
new { controller = "Post", action = "Update" },
new { httpConstraint = new HttpMethodConstraint("PUT") });
context.MapRoute(null,
"api/posts/{id}",
new { controller = "Post", action = "Delete" },
new { httpConstraint = new HttpMethodConstraint("DELETE") });
To a new person using ASP.NET MVC, it's very unintuitive to create anonymous objects to handle routing. I'd like to see it revised to something like this (and since we're using C# 4.0):
context.MapRoute("api/posts",
controller: "Post",
action: "Get",
httpMethodConstraint: HttpMethodConstraint.GET
);
context.MapRoute("api/posts",
controller: "Post",
action: "Insert",
httpMethodConstraint: HttpMethodConstraint.POST
);
context.MapRoute("api/posts/{id}",
controller: "Post",
action: "Update",
httpMethodConstraint: HttpMethodConstraint.PUT
);
context.MapRoute("api/posts/{id}",
controller: "Post",
action: "Delete",
httpMethodConstraint: HttpMethodConstraint.DELETE
);
This would make it more discoverable as well.
I'd like helpers that automatically scaffold index views. Maybe something like IndexDisplay(), IndexDisplayFor(), and IndexDisplayForModel().
I'd like templating to auto-generate buddy classes on any given model.
i also use simplicity feature like most of thing without helper such as html-helper i thing that development in asp.net MVC 3 is better way to learn MVC 3 in future.
The two things I'd like to see most are straightforward dependency injection in views, filters, etc., and (I know this is supposedly on the way with the Razor view engine) is to be able to test my views in isolation from the ASP.Net pipeline (perhaps including doctype validation and/or some type of JavaScript compiling/validation).
Here are a few other ideas:
It would be nice to be able to package up a UI component (views, templates, view models, etc.) for reuse across multiple projects. I'm guessing this is currently possible somehow, but I just don't need it badly enough to figure it out myself.
The idea of controllerless actions intrigues me, particularly from a SRP standpoint.
Better support for the Post-Redirect-Get (P/R/G) pattern... it just seems like there should be intrinsic support for this very important pattern.
more controls and helpers would be really nice, especially an (ajax) grid.
Asp.net MVC 3 Preview 1 was just announced as well at http://weblogs.asp.net/scottgu/archive/2010/07/27/introducing-asp-net-mvc-3-preview-1.aspx
I would like to see areas assembly support (I mean many assemblies with different areas) + dynamic loading, something like plugins.
Edit:
And we have preview 1 today: http://weblogs.asp.net/scottgu/archive/2010/07/27/introducing-asp-net-mvc-3-preview-1.aspx
Anybody happy ? :>
Related
I am asp.net Web Forms developer and i know the basics of Asp.net MVC. Developers talk about advantages of MVC but I haven't come across a clear or compelling description for using MVC over Asp.NET.
This is not duplicate question and i have gone through almost all
similar question but did not get clear description more in relation
with real life example. I do appreciate and expect the explanation of
each and every question mentioned below with real life example please
don't mark it as duplicate.
I know that you can not replace Asp.NET Web Forms with Asp.NET MVC still we have following advantages in MVC:
Separation of concerns (SoC): We can achieve it in asp.net also by adding BAL component in fact in MVC we do have to isolate business logic from controller action methods.Is SoC only applicable for Model-View-Controller separation in MVC? then what about business logic. Please provide real life example which will consider both Web Forms and MVC.
Enable full control over the rendered HTML: Web Forms also provide control over Html isn't it? Its considered that html rendering in Web Forms is more abstracted then what does html helper methods do in MVC. Anybody please explain it with example considering both Web Forms and MVC as i am getting more confused over this point.
Enable Test Driven Development (TDD): If you have separated your Business logic into BAL then you have achieved TDD? Is there any scenario where MVC would be accurate choice over webforms? Please provide example for same
No ViewState and PostBack events: We can manage viewstate in Web Forms which comes with cost of efforts, since in MVC we can maintain state by using Viewbag,Tempdata as web is stateless there is some mechanism that MVC maintains its state as hidden fields for Web Forms then how MVC Improves performance and page size in terms of statefullness? Example by considering Web Forms and MVC appreciated
Easy integration with jQuery: "Asp.NET Web Forms generate its custom id for controls" this is the only consideration for ease of integration of JavaScript frameworks? if yes then we can use ClientIDMode in asp.net control in Web Forms
1. Separation of concerns
SoC in MVC is not about separation business logic from UI. More importantly, it gives Controller main functions:
to fill View Model from Domain Model;
to handle View activity;
to show views depending on Domain logic.
View is responsible only for data representation in MVC.
It makes testing very simple as Controller operates pure View Model classes, opposed to WebForms which operates events and Form.
In WebForms View handles all UI activity and it basically makes decisions about scenario flow.
Here I'd like to mention that terms of View Model and Domain Model are different. Domain Model is a term describing all the services, Business logic and DAL hidden from Controller with some facade. And View Model is a class that encapsulates data required by View. It may be shared by Domain Model in simple cases. Why two classes?
Here are similar code snippets of ASP.NET MVC and WebForms doing the same things: 1) get data 2) handle data submission. In both cases I assume that IDomainModel is injected.
MVC:
public class SomeController : Controller
{
// injected
public IDomainModel Domain { get; set; }
public ViewResult Edit()
{
var record = Domain.GetRecord(1);
var dictionary = Domain.GetSomeDictionary();
var model = new SomeViewModel(record, dictionary);
return View(model);
}
[HttpPost]
public ActionResult Edit(SomeViewModel model)
{
if (ModelState.IsValid)
// save
return RedirectToAction("Result");
else
return View(model);
}
}
WebForms:
public partial class SomePage : System.Web.UI.Page
{
// injected
public IDomainModel Domain { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
var record = Domain.GetRecord(1);
var dictionary = Domain.GetSomeDictionary();
RecordId.Text = record.Id.ToString();
RecordName.Text = record.Name;
RecordDescription.Text = record.Description;
DicValue.DataSource = dictionary;
DicValue.DataValueField = "Id";
DicValue.DataTextField = "Value";
DicValue.SelectedValue = record.DictionaryEntryId.ToString();
DicValue.DataBind();
}
protected void btnSave_Click(object sender, EventArgs e)
{
var record = new RecordModel
{
Id = Int32.Parse(this.RecordId.Text),
Name = this.RecordName.Text,
Description = this.RecordDescription.Text,
DictionaryEntryId = Int32.Parse(this.DicValue.Text)
};
// save
}
}
Testing MVC controller Edit GET is incredibly simple:
[TestMethod]
public void EditGetTest()
{
SomeController target = new SomeController();
var record = new RecordModel { Id = 1, Name = "name1", Description = "desc1", DictionaryEntryId = 1 };
var dictionary = new List<SomeDictionaryEntry>
{
new SomeDictionaryEntry { Id = 1, Value = "test" }
};
target.Domain = new SimpleMVCApp.Models.Fakes.StubIDomainModel()
{
GetRecordInt32 = (id) => { return record; },
GetSomeDictionary = () => { return dictionary; }
};
var result = target.Edit();
var actualModel = (SomeViewModel)result.Model;
Assert.AreEqual(1, actualModel.Id);
Assert.AreEqual("name1", actualModel.Name);
Assert.AreEqual("desc1", actualModel.Description);
Assert.AreEqual(1, actualModel.DictionaryEntryId);
}
To test WebForms events we need to make a lot of changes and assumptions: we need to make the methods public, we need to initialize Form and its controls. It results in heavy hard-read tests which are impossible for 3) TDD.
2. Enable full control over the rendered HTML
I think this statement is a little bit exaggeration. Only HTML can give full control over rendered HTML. As for HtmlHelpers, DisplayTemplates and EditorTemplates, though the team made major improvements over 6 versions of the framework, it's still sometimes annoying to transform additionalViewData into html attributes.
For example, to pass some html attributes to an input you can't use #Html.EditorFor, you'll have to use #Html.TextBoxFor.
In the same time in ASP.NET you can specify any attributes on any elements and they will just render.
MVC:
Wrong:
#Html.EditorFor(m => m.Name, new { MySuperCustomAttribute = "Hello" })
Correct:
#Html.TextBoxFor(m => m.Name, new { MySuperCustomAttribute = "Hello" })
ASP.NET:
<asp:TextBox runat="server" ID="RecordName" MySuperCustomAttribute="hello"></asp:TextBox>
3. Enable Test Driven Development (TDD)
I think this statement is about testing of Controller vs Code-Behind. I covered this in 1.
4. No ViewState and PostBack events
ViewBag and ViewData are weak-typed facilities to pass data between Controller and Views. They are rendered as elements, nothing similar to ViewState. For example, in my View I initialize ViewBag.Title = "EditView"; which allows me to use this string on the Layout Page: <title>#ViewBag.Title - My ASP.NET MVC Application</title>. On the page it looks just like this <title>EditView - My ASP.NET MVC Application</title>
As to TempData, Session and Application, they are stored on server side. It's not rendered to page at all.
5. Easy integration with JQuery
I don't see how integration with JQuery becomes easier for MVC. Here is how we integrate JQuery into WebForms:
<script src="Scripts/jquery-1.8.2.min.js"></script>
<script>
$(document).ready(function () {
$('#DicValue').change(function () {
$('#ChosenValue').text($('#DicValue option:selected').val());
});
});
</script>
And here is almost the same snippet for ASP.NET MVC:
#section scripts{
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script>
$(document).ready(function () {
$('#DictionaryEntryId').change(function () {
$('#ChosenValue').text($('#DictionaryEntryId option:selected').val());
});
});
</script>
}
There is another point to mention about JQuery here: as ASP.NET MVC is pretty Opinionated framework, it becomes somewhat restrictive for extensive JS usage. It was originally designed for Scaffold Templates based development, and it is best with it. JQuery is good for ajax requests and for some minor logic in ASP.NET MVC, but when you start using it extensively, you end up with two controllers for every view: a C# one and a JS one. Hello, Unit Testing! Also JQuery(UI) is very good with its rich set of UI controls.
ASP.NET is designed with Postbacks in mind and they dictate you the basic application model. However, there are also different UI Toolkits for ASP.NET to make an application more dynamic and there is still some place for JQuery.
Wow, that was a long answer. Hope it'll help.
Ok.
I am developing applications in both frameworks i.e. Webforms and MVC, will be explaining things based on my experience.
Discipline is the most important thing that needs to be followed with any Architecture you are working on.
If you follow MVC correct and as per standards life would be super simple.
Lets go point by point.
Separation of concerns (SoC):
MVC provide Clean, organized and granular solution at various levels e.g.
There are multiple helper classes which hooks and does help in late bindings, you can mock controller using various plugins.
Easy to develop Helper classes.
Enable full control over the rendered HTML
Basically in MVC we have HTML in its native format, so you have more control over it and how it matters is it speeds up Page Load when you have lot of controls and data that are coming on the page.
And it matters when we are going with Web form architecture.
Enable Test Driven Development (TDD):
With discipline you can do it in both Architecture
No ViewState and PostBack events:
Viewstate puts extra load on page and in web forms when you see source of a page having lots of controls, grid etc, you will see huge viewstate.
If there is no viewstate life is just simple.
ViewData is at client side whereas others are at server side.
Easy integration with Jquery:
Indeed, MVC3, 4 have super better support for JQuery. There are lot of Predefined JQueries that are already introduced in templates.
Other than above points some additional points
Bundling
Refreshed and modernized default project templates
Better support of Mobile applications
Fast development
Code reusability
Least coupling within Layers
Good support to Ajax
Have a look at few links
http://www.codeproject.com/Articles/683730/New-Features-in-ASP-NET-MVC
http://www.asp.net/mvc/tutorials/hands-on-labs/whats-new-in-aspnet-mvc-4
Difference between ASP.NET MVC 3 and 4?
Here is the official answer from Microsoft for this question: http://www.asp.net/get-started/websites
I'd add to the top answers (which are generally correct) than MVC (and Web Pages) are both open source, so you have an easy access to the source code, bug database and can even PR bug fixes or features back (which we have taken in abundance).
At the end of the day it's a personal choice, and also depends on the experience you and your team has and if you have legacy code you want to reuse.
The MVC framework does not replace the Web Forms model; you can use either framework for Web applications. (If you have existing Web Forms-based applications, these continue to work exactly as they always have.)
Before you decide to use the MVC framework or the Web Forms model for a specific Web site, weigh the advantages of each approach.
Advantages of an MVC-Based Web Application
The ASP.NET MVC framework offers the following advantages:
It makes it easier to manage complexity by dividing an application into the model, the view, and the controller.
It does not use view state or server-based forms. This makes the MVC framework ideal for developers who want full control over the behavior of an application.
It uses a Front Controller pattern that processes Web application requests through a single controller. This enables you to design an application that supports a rich routing infrastructure.
It provides better support for test-driven development (TDD).
It works well for Web applications that are supported by large teams of developers and for Web designers who need a high degree of control over the application behavior.
Advantages of a Web Forms-Based Web Application
The Web Forms-based framework offers the following advantages:
It supports an event model that preserves state over HTTP, which benefits line-of-business Web application development. The Web Forms-based application provides dozens of events that are supported in hundreds of server controls.
It uses a Page Controller pattern that adds functionality to individual pages.
It uses view state on server-based forms, which can make managing state information easier.
It works well for small teams of Web developers and designers who want to take advantage of the large number of components available for rapid application development.
In general, it is less complex for application development, because the components (the Page class, controls, and so on) are tightly integrated and usually require less code than the MVC model.
Source http://msdn.microsoft.com/en-us/library/dd381412(v=vs.108).aspx
I'm a control developer and I'm trying to design a MVC.net control. When I researched some of the MVC controls like MVC toolkit, Telerik and DevExpress etc, I'm confuse which coding style is the popular way.
For example, Telerik has its own special coding style, just like this sample:
[Code1]
Html.Telerik().Calendar()
.Name("Calendar")
.Value((DateTime)ViewData["selectedDate"])
.MinDate((DateTime)ViewData["minDate"])
.MaxDate((DateTime)ViewData["maxDate"])
It uses dot till the end. While the DevExpress allows us using lambda expression to setting so that we can write code in the View.
[Code2]
#Html.DevExpress().GridView(
settings =>
{
settings.Name = "gvSorting";
settings.CallbackRouteValues = new { Controller = "GridView", Action = "SortingPartial" };
settings.Width = Unit.Percentage(100);
settings.Columns.Add("ContactName").SortOrder = DevExpress.Data.ColumnSortOrder.Ascending;
settings.Columns.Add("CompanyName");
settings.Columns.Add("City");
settings.Columns.Add("Region");
settings.Columns.Add("Country");
}).Bind(Model).GetHtml()
Or another option is writing code in the Action and store it in the ViewData or Model, so that the [Code1] can be like:
Html.NewWay(Model).Render()
In this way, we can write all code in the action side. So maybe users are familiar with it.
I hope if you have any ideas or experience, please feel free to talk about it.
Thanks,
Howard
As you say, there are different ways to do it. It all depends on what you want to do.
The Telerik style is known as "Fluent" notation, it's designed so that every configuration entry returns the a reference to the newly configured object, and you must guarantee you will never return null.
There is no one overriding style, people like different ways. Do whatever you think works best for you.
I have developed a plugin system that makes it easy to plug in new logic to an application. Now I need to provide the ability to easily add UI widgets.
There are already some good responses on how to create a portal system (like iGoogle) with ASP.NET MVC, and I'm fine about the overall concept.
My question is really about how we make strongly typed widgets.
Essentially when we set up a widget we define the controller and action names that are used to render that widget. We can use one controller action for widgets that are not strongly typed (since we just return PartialView(widgetControlName) without a model)
For widgets that are strongly typed (for example to an IList) we would need to add a new controller action (since I believe it is not possible to use Generics with ActionResult e.g. ActionResult).
The important thing is that the widget developers should not change the main application controllers. So my two thoughts are this:
Create new controllers in a separate class library
Create one partial WidgetController in the main web project and then extend this in other projects (is this even possible?) - not possible as per #mfeingold
As far as the development of the widgets (user controls) go, we can just use post build events from our extension projects to copy these into the Views/Widgets directory.
Is this a good approach. I am interested to here how others have handled this scenario.
Thanks
Ben
P.S - in case it helps, an example of how we can render widgets - without using Javascript
<%foreach (var widget in Model) {%>
<%if (widget.IsStronglyTyped) {
Html.RenderAction(widget.Action, widget.Controller);
} else {
Html.RenderPartial(widget.ControlName);
}
%>
<%} %>
For me it seems that MvcContrib's portable areas fits for developing independent widgets perfectly.
Here is an example - OpenId authentication widget.
Next week You can even watch c4mvc presentation about it.
The answer to your second question is NO. all source code for partial classes should be in the same project.
Is it possible with the templating engine to create a template for your widget type, then just call <%: Html.EditorForModel(untypedWidgetModel) %> - in theory, your template for that type would then take over and render appropriate HTML.
Or have I misunderstood how templating can work?
We're evaluating asp.net MVC and are looking for some more complicated examples over and above NerdDinner.
Specifically, in a more complex web app, I might have a navigation bar (including primary nav, a search box and a log-in status display), a main content area, a sub-content area (including related content) and a footer. In MVC a controller returns a ViewModel (not a View if I'm thinking that I want to de-couple my Controller from my View) - would my ViewModel have to have properties to cover each and every aspect of the "page" I am aiming to render as output?
If this is unclear, I may be able to re-word my question.
BTW - I know this site is built using MVC. I'm after downloadable examples.
Thanks in advance.
Take a look at CodeCampServer.
Edit: With reference to your query about view models, this isn't the perfect answer to it but thought I'd draw attention to AutoMapper (used by CodeCampServer) which can assist with auto mapping data between models and view models which is a real time saver. Also worth considering the concept of Input Builders (there's some available with MVCContrib and also some in ASP.NET MVC 2) which will also reduce the amount of data you have to pass into a view by encapsulating common functionality across the board.
There's a good video on the ASP.NET MVC 2 offering here: http://channel9.msdn.com/posts/Glucose/Hanselminutes-on-9-ASPNET-MVC-2-Preview-1-with-Phil-Haack-and-Virtual-Scott/.
Here ya go:
<% Html.RenderAction<LayoutController>(c => c.SearchBox()); %>
<% Html.RenderAction<LayoutController>(c => c.NavBox(Model)); %>
Put these in your masterpages, or on specific views for sidebar widgets, and abstract their logic away from your controller/viewmodel you are working on. They can even read the current RouteData (url/action) and ControllerContext (parameters/models), cause you are dealing with ambient values in these objects - and executing a full ActionMethod request!
I blogged about this little known secret here. I also blogged about where this is located, which is the ASP.NET 1.0 MVC Futures assembly that is a seperate add-on from Microsoft.
Steve Sanderson actually gives gives examples of complex logic and application building in a book I have called Pro ASP.NET MVC (shameless plug, I know, but it's what you are looking for in your question), where he actually uses the RenderAction! I made the blog post, before I even read the book so I am glad we are on the same page.
Actually, there are dozens of extensions and functionality that was developed by the ASP.NET MVC team that was left out of the ASP.NET MVC 1.0 project - most of which makes complex projects much more managable. This is why more complex examples (list above in most people's answers) have to use some type of custom ViewEngine, or some big hoop jumping with base controllers and custom controllers. I've looked at almost all of the open source versions listed above.
But what it comes down to is not looking at a complex example, but instead knowing the ways to implement the complex logic that you desire - such as your Navigation bar when all you have is a ViewModel in a single controller to deal with. It gets tiring very quickly having to bind your navbar to each and every ViewModel.
So, an example of these is the Html.RenderAction() extension (as I started off with) that allows you to move that more complex/abstracted logic off of the viewmodel/controller (where it is NOT even your concern), and place it in its own controller action where it belongs.
This littler baby has saved MVC for me, especally on large scale enterprise projects I am currently working on.
You can pass your viewmodel into the RenderAction, or just render anything like a Footer or Header area - and let the logic be contained within those actions where you can just fire and forget (write the RenderAction, and forget about any concern of what it does for a header or footer).
You are welcome to take a look at good.codeplex.com
It has much of what you seek above but there is work to be done! However, after you've looked I'd be happy to field questions on it here or over on codeplex.
This is what mygoodpoints.org is currently running on.
would my ViewModel have to have
properties to cover each and every
aspect of the "page" I am aiming to
render as output?
Yes. There is another option with RenderAction, but apart from that a ViewModel in generall is often big and you have to find a good way to fill it. I admit this sounds like a trouble spot first.
AtomSite is a blog engine written using ASP.NET MVC
As far as I know, a Controller directly returns a View and can pass data to the View using either the ViewData or the Context.
The former is just a loose bag of various bits of data, whereas the latter is a specific type.
The ViewModel would be passed to the View as the Context (and the mark-up of the View would be strongly-typed to the type of ViewModel it expects).
That's my 2c worth :) Hope that helped-- sorry I could not include any downloadable examples.
To automatically pass data to all views, you can make your own controller class and use that:
Example
public class MyController : Controller
{
private User _CurrentUser;
public User CurrentUser
{
get
{
if (_CurrentUser == null)
_CurrentUser = (User)Session["CurrentUser"];
return _CurrentUser;
}
set
{
_CurrentUser = value;
Session["CurrentUser"] = _CurrentUser;
}
}
/// <summary>
/// Use this override to pass data to all views automatically
/// </summary>
/// <param name="context"></param>
protected override void OnActionExecuted(ActionExecutedContext context)
{
base.OnActionExecuted(context);
if (context.Result is ViewResult)
{
ViewData["CurrentUser"] = CurrentUser;
}
}
}
I am currently building an application using ASP.NET MVC. The data entry pages are fairly easy to code, I just make the Model for the page of the type of my business object:
namespace MyNameSpace.Web.Views.ProjectEdit
{
public partial class MyView : ViewPage<Project>
{
}
}
Where I am struggling is figuring out the best way to implement a dashboard like interface, with stand-alone parts, using ASP.NET MVC, where the Model for each part would be different? I'm assuming that each part would be an MVC user control.
Also, how could I make it so each part is testable?
I think that user controls is probably the way to go. I'm not sure what the concern is about testability. You should be able to test that your controller is providing the right view data -- since you'll have several models each of these will probably be stored in a separate view data item, rather than aggregating them in a single model. Aggregating in a single model is also possible, although probably more brittle. Each control would just need to check for a particular view data item, rather than being specific to a particular model. You could approximate the model variable on each view page by doing:
<% MyUserControlModel model = ViewData["MyUserControlModel"]
as MyUserControlModel; %>
<div id="myUserControl_dashboard" class="dashboard">
Name: <%= model.Name %><br />
Count: <%$ model.Count %>
</div>
If you need to test your view, then you're probably already using Selenium or some other web testing framework. I don't think that these would care how the page was constructed and you should be able to construct your tests pretty much like you always do.
Check out the notion is sub-controllers in MVC-Contrib http://www.codeplex.com/MVCContrib. Basically you run a full request to a partial then display that partial where you want in your existing code.
Alternatively you can check out this post: http://blog.codeville.net/2008/10/14/partial-requests-in-aspnet-mvc/
Codeplex.com has an open source project "DotNet.Highcharts". This project provides an ASP.NET control that wraps around the excellent (free for personal use) Highcharts charting library. that includes a sample MVC3 project in the downloads section.
URL: http://dotnethighcharts.codeplex.com/
I have posted an article on CodeProject.com that includes a downloadable VS2012 solution and some sample C# code. However I use a webform template in my example, not MVC. The bulk of the dashboard is done using JavaScript libraries, HTML & CSS. I have included some sample C# code to demo data retrieval in C# which in then merged with JavaScript code to render one of the many dashboard charts.