Telerik Controls with ASP.NET MVC: Does this violate the MVC model? - asp.net-mvc

Will using MVC enabled Telerik controls with
ASP.NET MVC violate the MVC model?
And if not, what kind of performance
hit (versus features and development speed) will there be with using
Telerik controls over manually
coding the HTML?

Since I am the person who built that demo I think I can share my opinion as well. This sample application does not violate the MVC principles according to me. RadControls do not rely on ViewState or postbacks in MVC applications (you can check the generated output to see for yourself - no __doPostBack or __VIEWSTATE). Indeed you need to write some code to bind the grid or populate the menu - but still the code is in the View (ASPX) and is entirely related with the presentation (again this is just my opinion so I might be wrong).
I should also mention that there are some limitations indeed - some of the built-in features (that rely on postback) do not work in MVC. However will work on resolving them. Feel free to open a support ticket or forum thread should you have any particular questions with regards to RadControls and ASP.NET MVC.

To your second question, regarding performance hit vs. manual coding, I think it depends on the control you're using. For example, if you use any of the Telerik navigation controls in MVC- such as Menu, TabStrip, or PanelBar- you'll save yourself a TON of manual coding (since a menu/tabstrip/etc. requires a lot of client-side code to provide the interactive features (like drop down options) and a lot of complex CSS). So, the RadControls in MVC will help restore the -productivity- you're used to when building rich ASPNET apps.
For more complex controls, like the Grid, which depend a lot on postbacks, you're mainly benefitting from the provided styling. To fit the MVC model, controls like the Grid require quite a bit of "custom" coding to "convert" postback events to URL actions, so you may not save a lot of code vs. a MVC grid template. You -will- save a lot of time on styling, though, and the performance difference should be negligble.
Hope that helps.
-Todd

I'm pretty sure that these rely on the PostBack model in WebForms and wouldn't be compatible with MVC views. You could probably find a way for them to work, but it wouldn't be in keeping with the MVC principles. You can mix/match WebForms with MVC Views in the same web site if needed, but I wouldn't recommend it.
What you will lose by using the Telerik controls are most of the benefits of MVC: clear separation of concerns, enhanced testability, leaner HTML, a cleaner architecture. It wouldn't surprise me to find that eventually Telerik comes out with controls for MVC. For now, I'd look at either pure Javascript implementations for client-side or hand-coded ViewUserControls if you need to reuse some common components.

Personally, I wouldn't use the current telerik controls with MVC. I think they work in some situations (http://telerikwatch.com/2009/01/telerik-mvc-demo-app-now-available.html), but I think they are quite viewstate / postback centric. Knowing telerik, they will come out with a MVC compatible version, but looks like they have a lot of work in front of them...

I realize this is an old question, but Telerik's ASP.NET MVC controls are simply controls, like datepickers, grids, panelbars, tabstrips. These are not in rival to the MVC framework. They work in conjunction with it. Your question tells me you do not, or at least did not, understand what MVC really is.
For the benefit of others that may be confused, as well, MVC stands for Model-View-Controller. There's a Model, that represents objects you are using for storage or retrieval of values, a View, that displays those object values and can be used to set them through use of controls, such as Telerik's datepickers, grids, and such, and the Controller, that houses the functions that render the views and interacts with the model elements. The controls you use for updating the model must be able to interact with that model to be MVC-compliant. If they did not, they could not be advertised as MVC controls, in the first place, so yes, their controls work with, and do not "violate", the MVC framework.
Here is one such use of a datepicker control, in conjunction with a model:
VIEW:
#model MyViewModel
<%= Html.Kendo().DateTimePickerFor(model => model.ExpirationDate)
.Name("datetimepicker")
.Value(model.ExpirationDate)
%>
VIEWMODEL: (or Model)
public MyViewModel() {
public DateTime ExpirationDate { get; set; }
}
CONTROLLER:
public ActionResult Index(int id)
{
var data = dataContext.SomeTable.Where(e => e.ID == id).FirstOrDefault();
// return View(data); // this would allow you to use #model SomeTable
// in your view, and not require a ViewModel, but returns the whole
// record for the given ID
// ViewModels allow you flexibility in what you return
MyViewModel mvm = new MyViewModel();
mvm.ExpirationDate = data.ExpirationDate;
return View(mvm);
}
For coding them using Telerik's demos, it is a lot of copy/paste and various small edits for your specific model and data you are entering (as shown above). There is also far less code because of the controls have most everything built-in, so of course production time is cut way down, things like filtering, paging, sorting in grids is already there - you turn it on just by adding say, Filterable(), for filtering. Instead of having to create, say, individual DataColumns and add them to a DataTable, then bind that to a grid, then worry about individual OnDataBound events (which you could still do, but need less of), you instantiate a grid, add your columns, set your controller functions for creating, reading, updating, and deleting items, and set any properties on the grid, and you are done:
<%: Html.Kendo().Grid<Models.ViewModels.MyViewModel>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(c => c.ExpirationDate).Format("MM/DD/YYYY");
})
.HtmlAttributes(new { style = "height: 380px;" })
.Scrollable()
.Sortable()
.Filterable()
.Pageable(pageable => pageable
.Refresh(true)
.PageSizes(true)
.ButtonCount(5))
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("Customers_Read", "Grid"))
.Create(create => create.Action("Customers_Create", "Grid"))
.Update(update=> update.Action("Customers_Update", "Grid"))
.Delete(delete => create.Action("Customers_Delete", "Grid"))
)
%>
The "read" is as simple as taking those first 2 lines in the public ActionResult Index() above and putting them into a public Customers_Read([DataSourceRequest] DataSourceRequest request) {} function that returns data as .ToDataSourceResult(). Updating is similar to the last 3 lines in that function, since you instantiate the model, copy the values from the model that is passed in from the grid, then do something like dataContext.SaveChanges() to save. Once saved, the grid automatically does another read, so it will see the latest values. No need for anything else to run on postback to rebind the data, so no more code to write.
Just look at the code examples here to give a better idea: http://demos.telerik.com/aspnet-mvc/

Related

Why Asp.NET MVC over Asp.NET Web Forms

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

ASP.NET WEB API Multiple Interfaces

I am designing ASP.NET WEB API service with two interfaces. First interface is read-only and second one is admin interface (to be used with MVC app) with full CRUD support. Does anyone know where I can get more information on such setup, any tutorials, walk thought, sample design document?
Also does it worth splitting these into two interfaces or keep them in same? But problem is that in read-only I expose 2-3 properties for every object while for admin there are 10-15?
Similar setup for WCF or design spec will do.
If I understand what your wanting to do, may I suggest rather than having one URL, i.e. \dataStuff\dataView split off into another view, maybe \dataStuff\edit\ which only admin's have access to, can be done like so:
[Authorize(Roles = "Administrators")]
public ActionResult edit()
{
return View();
}
then next to each data element that your viewing add the following to ONLY admin's through use of User.IsInRole
#foreach (var item in Model.dataTable)
{
#*
write a value from the data table here
*#
#Html.ActionLink("edit", "edit").If(User.IsInRole("Administrators"))
<br/>
}
obviously you don't have to display your data like this, I'm just showing that you add to the end of each element of the database an edit ActionLink IF the user is admin.
This allows your admin to view data like a user and also have the added functionality they need. Code re-use is better than a single view which has two states, Admin and non Admin.
Sorry if this isn't the best explanation, fairly new to MVC
Seems like this concept is sometimes called CQRS.
Sample: http://martinfowler.com/bliki/CQRS.html

Using #HTML.EditorForModel & DisplayForModel with ViewModels in MVC

Coming from a Silverlight background, MVVM is solidly planted in my mind. Moving to MVC, although rewarding, has been something of a paradigm shift for me.
One of the questions I have is about using EditorForModel when the strongly typed view has been passed a ViewModel with the object to be editted as a property, rather than the POCO being directly passed in as the model, with no viewmodel encapsulated around it.
How can I use EditorForModel on a property of the model, rather than the whole model itself? I went looking for something akin to #HtmlHelper.EditorForModel(model.Customer), but coulndt find an overload. It seems you can only generate an editor for the whole model...
(where customer is a good 'ol poco)
You could try -
#Html.EditorFor(m => m.Name)

asp.net MVC - complex example?

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;
}
}
}

Is there an equivalent to Monorail view components for the ASP.Net MVC Framework?

I make heavy use of View Components in some of the larger applications I've built in Monorail - What is the equivalent approach in ASP.Net MVC for a view component, that can support sections etc.?
Actually you have several options to create the equivalent of a ViewComponent in ASP.NET MVC, depending in the complexity of your component. I use these two approaches which are the more mvc-ish of the options I am aware of.
1:
The simplest thing is to create a ViewUserControl and display it using Html.RenderPartial with the helper. The ViewUserControl is a simple piece of markup with no backing controller (I think you can put a codebehind file if you want).
Optionally, you can pass a model object or the entire ViewData dictionary to the view when calling RenderPartial, like this:
<% Html.RenderPartial("TopBar", model); %>
"TopBar" is an ascx page. This works anywhere, in master pages and in normal views.
2:
If you want your component to have more complicated logic or to access datasources, IoC, etc, then you can use Html.RenderAction which is an extension method found in the Microsoft.Web.Mvc assembly. I am using this out of the mvccontrib distribution. It works like this, you need to create a normal controller with all the logic you need, then create some views and all of these things become your component, for example:
public class AboutComponentController : Controller {
public IRepository Repository{ get; set; }
public ActionResult Detail() {
var lastEvent = Repository.FindAll<Auditoria>().FirstOrDefault();
return View(lastEvent);
}
}
Notice how I have a reference to an IRepository which is going to be injected with IoC (Windsor in my case) and I can do anything a normal controller would do.
Now, in any page (master or normal) where you want to use your component, import Microsoft.Web.Mvc and call Html.RenderAction with the appropriate parameters. This will create a mini mvc pipeline that creates the controller, resolves the view, etc., just like a Monorail ViewComponent. I prefer to use the lambda based variation of the method, like this:
<% Html.RenderAction<AboutComponentController>(x => x.Detail("a message"));%>
Unfortunately, the only way to pass parameters is to use the method call itself, which in turn must be unique in the controller. Still needs some work to resemble a ViewComponent.
I don't use masterpages or layouts in the views of my components since they are composition elements themselves.
Remember that when using the Webforms view engine, you can have strongly typed views if you like to have intellisense when using the Model variable in code blocks.
The beauty of this is that you can mix view engines with these approaches, I usually create the components in nvelocity and display them in aspx pages, etc.
I now there can be issues with caching of the partial views but I haven't run into any so far. I am sure there are other options (like subcontrollers in mvccontrib) but this is usually enough for simple cases. Of course you can use normal ASP.net components in your aspx view pages but that would be cheating right? hehe. I hope it helps.
Phil Haack blogged about creating areas to group controllers into sub-folders/sections similar to MonoRails.

Resources