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
Related
I am new to ASP.NET MVC, I heard about the 3rd party of DevExpress for MVC.
I use both general helpers (for example #Html.TextBox("Name")) and DevExpress helpers like:
#Html.DevExpress().TextBox(
settings => {
settings.Name = "textBox2";
settings.Width = 170;
settings.Properties.NullText = "Enter your name...";
}
).GetHtml()
in basic level applications. But both are working in a similar way.
I'm unable to understand the benefits of using DevExpress helpers in ASP.NET MVC ...
Thanks
I'm unable to understand the benefits of using DevExpress helpers in ASP.NET MVC ...
You can try to compare the capabilities before and decide after.
Regarding the simplest case (TextBox extension) - take a look at the TextBox Main Features documentation. The benefits are: display formatting, mask-input, built-in validation, themes... To discover these features in action, please take look at the corresponding demo.
My title sums this up pretty well. My first though it to provide a few data formats, one being HTML, which I can provide and consume using the Razor view engine and MVC3 controller actions respectively. Then, maybe provide other data formats through custom view engines. I have never really worked in this area before except for very basic web services, very long ago. What are my options here? What is this Web API I see linked to MVC4?
NOTE: My main HTML app need not operate directly off the API. I would like to write the API first, driven by the requirements of a skeleton HTML client, with a very rudimentary UI, and once the API is bedded down, then write a fully featured UI client using the same services as the API but bypassing the actual data parsing and presentation API components.
I had this very same thought as soon as the first talk of the Web API was around. In short, the Web API is a new product from the MS .NET Web Stack that builds on top of WCF, OData and MVC to provide a uniform means of creating a RESTful Web API. Plenty of resources on that, so go have a Google.
Now onto the question..
The problem is that you can of course make the Web API return HTML, JSON, XML, etc - but the missing piece here is the Views/templating provided by the Razor/ASPX/insertviewenginehere. That's not really the job of an "API".
You could of course write client-side code to call into your Web API and perform the templating/UI client-side with the mass amount of plugins available.
I'm pretty sure the Web API isn't capable of returning templated HTML in the same way an ASP.NET MVC web application can.
So if you want to "re-use" certain portions of your application (repository, domain, etc), it would probably be best to wrap the calls in a facade/service layer of sorts and make both your Web API and seperate ASP.NET MVC web application call into that to reduce code.
All you should end up with is an ASP.NET MVC web application which calls into your domain and builds templated HTML, and an ASP.NET Web API application which calls into your domain and returns various resources (JSON, XML, etc).
If you have a well structured application then this form of abstraction shouldn't be a problem.
I'd suggest developing your application in such a way that you use a single controller to return the initial application assets (html, javascript, etc) to the browser. Create your API / logic in WebAPI endpoint services and access those services via JavaScript. Essentially creating a single page application. Using MVC 4 our controller can return different Views depending on the device (phone, desktop, tablet), but using the same JavaScript all of your clients will be able to access the service.
Good libraries to look into include KnockoutJS, SammyJS , or BackBoneJS
If you do have a requirement to return HTML using the WebAPI e.g. to allow users to
click around and explore your API using the same URL then you can use routing\an html message handler.
public class HtmlMessageHandler : DelegatingHandler
{
private List<string> contentTypes = new List<string> { "text/html", "application/html", "application/xhtml+xml" };
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (request.Method == HttpMethod.Get && request.Headers.Accept.Any(h => contentTypes.Contains(h.ToString())))
{
var response = new HttpResponseMessage(HttpStatusCode.Redirect);
var htmlUri = new Uri(String.Format("{0}/html", request.RequestUri.AbsoluteUri));
response.Headers.Location = htmlUri;
return Task.Factory.StartNew<HttpResponseMessage>(() => response);
}
else
{
return base.SendAsync(request, cancellationToken);
}
}
}
For a full example check out:-
https://github.com/arble/WebApiContrib.MessageHandlers.Html
I've played with this idea before. I exposed an API through MVC3 as JSONResult methods on different controllers. I implemented custom security for the API using controller action filters. Then built a very AJAX heavy HTML front-end which consumed the JSON services. It worked quite well and had great performance, as all data transferred for the web app was through AJAX.
Frederik Normen has a good post on Using Razor together with ASP.NET Web API:
http://weblogs.asp.net/fredriknormen/archive/2012/06/28/using-razor-together-with-asp-net-web-api.aspx
One important constraint of a well designed REST service is utilizing "hypermedia as the engine of application state" (HATEOAS - http://en.wikipedia.org/wiki/HATEOAS).
It seems to me that HTML is an excellent choice to support as one of the media formats. This would allow developers and other users to browse and interact with your service without a specially built client. Which in turn would probably result in the faster development of a client to your service. (When it comes to developing actual HTML clients it would make more sense to use a json or xml.) It would also force a development team into a better designed rest service as you will be forced to structure your representations in such a way that facilitates an end users navigation using a browser.
I think it would be smart for any development team to consider taking a similar approach to Frederik's example and create a media type formatter that generates an HTML UI for a rest service based on reflecting on the return type and using conventions (or something similar - given the reflection I would make sure the html media format was only used for exploration by developers. Maybe you only make it accessible in certain environments.).
I'm pretty sure I'll end up doing something like this (if someone hasn't already or if there is not some other feature in the web api that does this. I'm a little new to Web API). Maybe it'll be my first NuGet package. :) If so I'll post back here when it's done.
Creating Html is a job for an Mvc Controller not for Web Api, so if you need something that is able to return both jSon and Html generated with some view engine the best option is a standard Mvc Controller Action methosd. Content Negotiation, that is the format to return, can be achieved with an Action Fiter. I have an action filter that enable the the controller to receive "hints" from the client on the format to return. The client can ask to return a view with a specific name, or jSon. The hint is sent either in the query string or in an hidden field (in case the request comes from a form submit). The code is below:
public class AcceptViewHintAttribute : ActionFilterAttribute
{
private JsonRequestBehavior jsBehavior;
public AcceptViewHintAttribute(JsonRequestBehavior jsBehavior = JsonRequestBehavior.DenyGet)
{
this.jsBehavior = jsBehavior;
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
string hint = filterContext.RequestContext.HttpContext.Request.Params["ViewHint"];
if (hint == null) hint = filterContext.RequestContext.RouteData.Values["ViewHint"] as string;
if (!string.IsNullOrWhiteSpace(hint) && hint.Length<=100 && new Regex(#"^\w+$").IsMatch(hint) )
{
ViewResultBase res = filterContext.Result as ViewResultBase;
if (res != null)
{
if (hint == "json")
{
JsonResult jr = new JsonResult();
jr.Data = res.ViewData.Model;
jr.JsonRequestBehavior = jsBehavior;
filterContext.Result = jr;
}
else
{
res.ViewName = hint;
}
}
}
base.OnActionExecuted(filterContext);
}
}
Now that it's been a little while through the Beta, MS just released the Release Candidate version of MVC4/VS2012/etc. Speaking to the navigation/help pages (mentioned by some other posters), they've added a new IApiExplorer class. I was able to put together a self-documenting help page that picks up all of my ApiControllers automatically and uses the comments I've already put inline to document them.
My recommendation, architecture-wise, as others have said as well, would be to abstract your application into something like "MVCS" (Model, View, Controller, Services), which you may know as something else. What I did was separate my models into a separate class library, then separated my services into another library. From there, I use dependency injection with Ninject/Ninject MVC3 to hook my implementations up as needed, and simply use the interfaces to grab the data I need. Once I have my data (which is of course represented by my models), I do whatever is needed to adjust it for presentation, and send it back to the client.
Coming from MVC3, I have one project that I ported to MVC4, which uses the "traditional" Razor markup and such, and a new project that will be a single page AJAX application using Backbone + Marionette and some other things sprinkled in. So far, the experience has been really great, it's super easy to use. I found some good tutorials on Backbone + Marionette here, although they can be a bit convoluted, and require a bit of digging through documentation to put it all together, it's easy once you get the hang of it:
Basic intro to Backbone.js: http://arturadib.com/hello-backbonejs/docs/1.html
Use cases for Marionette views (I found this useful when deciding how to create views for my complex models): https://github.com/derickbailey/backbone.marionette/wiki/Use-cases-for-the-different-views
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 building what will primarily be a mobile browser targeted ASP.NET MVC application. Although it will target the desktop as well in a smaller capacity. (I'm fairly new to both MVC and mobile apps.)
I'm wondering what is the best practice for segregating mobile vs. desktop users in an MVC application.
Should the controller be in charge of checking for browser type? Or, should this type of functionality be reserved for the View?
If checked in the view, can & should a masterpage do the checking? Do you know of any good examples online?
Update:
I just discovered an overload of the View method that accepts a string argument specifying the Masterpage to be used.
For example:
public ActionResult Index()
{
if (isMobile())
return View("Index", "Mobile", myObject);
else
return View("Index", myObject);
}
To me this suggests that at least a few people on the Microsoft team expect major distinctions (such as mobile vs. desktop) to be carried out in the controller. (There's a good chance I'm highly confused about this.)
I think the controller must know the plataform, because you can get a lot of views in distint languages, Some view for browsers (mobile) another view in Desktop App, another view can be a web service, and all views can have different needs.
If you have a few views, you can call views with parameters to mark the type of view:
Index(mobile) and Index(Desktop) as it:
Index(string typeOfApp){
//prepare data, do querys, etc
if (typeOfApp=='Mobile'){
redirectoAction('IndexMobile',ds);
//or
return view('IndexMobile',ds)
}
return View('IndexDesktop',ds);
}
IndexMobile(DataSet ds){}
IndexDesktop(DataSet ds){}
You can get a general method for your action() and another action for every type,
Index -> Index4Mobile & Index4Browser & Index4Desktop
And in all of this methods prepare or do something special for every plataform, or a Single Action with multiple views(1 for plataform).
Any code dealing with rendering of your code should exist on the page itself via CSS and javascript. Your controllers should know nothing about how your data will be rendered on screen. The views shouldn't really even know anything about it either - they only expose the data that your CSS will render.
The HTML your View spits out describes your data and how it is organized. Only the CSS should know how to make it look appropriate for whatever device is rendering it.
This link, chock full of javascript should help determine which mobile browser is running.
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/