ASP.NET MVC: For Those Who Dislike Reusability
-
The problem with moving from Web Forms to MVC is that it is a different architecture and requires you to think about your application is a different way. Web Forms is Microsoft's way of making a stateless protocol, HTTP, appear to have state. They do this by storing a the page state in a hidden value so it is available to the server on Postback, and then simulate the event architecture that is familiar to Windows Forms (VB) programers. The page gets control first and there is one 'code-behind' for each page. MVC, on the otherhand, requires the developer to get their hands a little dirtier, and work with the 'low-level' HTML. Your web pages should only be responsible for displaying/formatting the data passed in in the Model. The Controller is responsible for getting the information, building up a Model and passing it to the page for display. The controller gets control first, and each controller is the 'code-behind' for multiple Views (pages). Additionally, ASP.NET MVC will parse out your Form Data, to build up instances of classes for you, along with validating the information for you. This greatly reduces the amount of code you need to write, and helps get you business logic out of your presentation layer. As for re-useable components, MVC supports re-use of UI in varioius ways:
- Code Generation Templates - by using intellegent code generation templates you can create Views, Partial Views, Classes, almost anything you want. MVC even allows you to plug in your own custom template and they will be included in the list of View types. Similarily, you can have templates for Controllers, so you could have Controllers that use the Repository Pattern, use Entity Framework, implement a Web API, etc.
- Display and Edit Template - you can create templates that control how classes are rendered when using the @Html.DisplayFor or @Html.EditorFor helper. For example, you could have all Date fields use a JQuery UI DatePicker.
- Partial Views - Allows you to create a page for rendering a piece of the UI, not the whole page. They are similar to UserControls in this manner, but remember, it is the Controller, not the page that handles the Http Requests. Partials can be passed an object which acts as a Model for the page implementing the Partial View.
- Render Action - Allows the View to cause a new instance of a Controller to be spun up and a method called to generate HTML for the main page. This means that the new Controller does all the work to build up the c
Yes! Exactly. And I think that it's 'regular' html and javascript is a benefit not a limitation. Especially when compared with the hidden complexities of asp.net ajax (embedded javascript in resource files, that happens to be minified, in case you decide to get cute with a client side debugger.) It is a different way to think about it. And there's an elephant in the room: really, come on, who re-uses user control code anyway? When is the last time your web user controls were ACTUALLY re-usable? Ok, maybe on different pages in one app, but that's exactly like partial views. I upvote in your general direction, Mr. Dennis.
-
After reading an 800-page book on MVC and just now starting to get my hands dirty, I still have seen no clear way to make reusable user controls in MVC. Sure, one can create a partial view and use some AJAX so that the view can update itself by calling the appropriate controller/action. But if the user doesn't have JavaScript enabled, they're screwed. And I could pass around the main view name to the partial view, but then I'm either passing more details than I'd like to the client or I'm using session, which is best to avoid in a server farm situation (not to mention instantiating the proper model could prove troublesome). And I could have the partial view post to an action method on the parent view's controller, but then I have to do that for every page that makes use of the partial view. What a nightmare. I think I'll go back to ASP.NET web forms. :|
I for one wished I didn't invest the time I did learning MVC as I find myself back using web forms and the tried and tested ado.net classes. This was wasted time and money for me. There is always Web forms MVP which is the way I would go now.
-
After reading an 800-page book on MVC and just now starting to get my hands dirty, I still have seen no clear way to make reusable user controls in MVC. Sure, one can create a partial view and use some AJAX so that the view can update itself by calling the appropriate controller/action. But if the user doesn't have JavaScript enabled, they're screwed. And I could pass around the main view name to the partial view, but then I'm either passing more details than I'd like to the client or I'm using session, which is best to avoid in a server farm situation (not to mention instantiating the proper model could prove troublesome). And I could have the partial view post to an action method on the parent view's controller, but then I have to do that for every page that makes use of the partial view. What a nightmare. I think I'll go back to ASP.NET web forms. :|
Mvc resusable controles are not dependent on ajax. Use uihint attribute over the property on which the control is to be rendered. In uihint pass the partial view name. In view page use editorfor to render that property. The partial view will be rendered automaticaly. The property will act as model to that partial view so make sure the datatype of the property and the model of the view is same.
-
After reading an 800-page book on MVC and just now starting to get my hands dirty, I still have seen no clear way to make reusable user controls in MVC. Sure, one can create a partial view and use some AJAX so that the view can update itself by calling the appropriate controller/action. But if the user doesn't have JavaScript enabled, they're screwed. And I could pass around the main view name to the partial view, but then I'm either passing more details than I'd like to the client or I'm using session, which is best to avoid in a server farm situation (not to mention instantiating the proper model could prove troublesome). And I could have the partial view post to an action method on the parent view's controller, but then I have to do that for every page that makes use of the partial view. What a nightmare. I think I'll go back to ASP.NET web forms. :|
Have you looked at the helper method called @HTML.Action("ActionName", "ControllerName")? You can embed those on your _Layout (i.e. master) page as well as other views. It doesn't change the URL and allows you to grab data it its own controller separately from the host page. I use it with good success.
-Brian Hall-
-
After reading an 800-page book on MVC and just now starting to get my hands dirty, I still have seen no clear way to make reusable user controls in MVC. Sure, one can create a partial view and use some AJAX so that the view can update itself by calling the appropriate controller/action. But if the user doesn't have JavaScript enabled, they're screwed. And I could pass around the main view name to the partial view, but then I'm either passing more details than I'd like to the client or I'm using session, which is best to avoid in a server farm situation (not to mention instantiating the proper model could prove troublesome). And I could have the partial view post to an action method on the parent view's controller, but then I have to do that for every page that makes use of the partial view. What a nightmare. I think I'll go back to ASP.NET web forms. :|
I'm going to throw this into the ring and see where it lands, so no thrashing. I'm just now doing heavy research on MVC3 as well. And I'm very interested in re-usable controls in MVC. That is how we currently do it in web forms. BUT, the control is linked to the parent page through events. For example, I click "Save" on the control, and it fires an event that is registered on the parent, to execute a method and in the method it basically fire the "Save" method on the control, plus whatever actions it needs to do (hide panels, display things, whatever) on the parent. ANYHOO, is there no way to register events like this between Views? Or is that the AJAX part everyone keeps mentioning? Personally, I agree with the OP and tend to avoid JavaScript whenever possible because the user can turn it off, and then you have a failed app.
-
The url doesn't change. What are you talking about? The thing you MIGHT be passing around through those massive security holes called URL's is the route to the controller actions. GASP! People who are complaining about MVC are probably the same ones who have not really figured out how it works. Personally, the biggest benefit of MVC for me is that I get to work with regular html and javascript. It's not like you have to know two ways of looking at the world anymore: one, the rendered way (what it looks like on the browser) and two the web forms markup way. The C# code just wires up the markup with minimal template like instructions versus an entirely new 'dialect' of xml elements you must memorize. Granted it's not so hard once you get used to web forms to remember these xml thingies, but, the black boxy-ness sometimes is an issue. For example, simple things that are heavily abstracted so that the developer never thinks about it, like control extenders, you may never know just wtf is wrong with your auto-complete extender inside a tab panel under lock and key of an update panel, so when troubleshooting it you start doing things like digging into the embedded resource javascript files (which are kindly minified for performance) from the extenders and want to puke all over yourself. IF you are going to use a lot of ajax I think you're crazy if you don't go with MVC. If you're only using a lot of datagrids and I can why you like webforms better. The webforms grids with entity data sources are easier for quick and dirty deployments. I'm going to hammer this again: People don't pass the name of the view to the client. I have no idea where people get this insane idea. The ViewBag is ONLY alive during the execution of the request. It never makes it to the client, kids. It's not ViewState. That's the dangerous bit, ViewState.
dave.dolan wrote:
The url doesn't change.
Yes it does. Here, I'll give you an example. Suppose I create a new MVC 3 Internet project and delete most of the files. The remaining (important) files/folders are this:
- Controllers
- AccountController.cs
- HomeController.cs
- Models
- AccountModels.cs
- Views
- Account
- LogOn.cshtml
- Home
- Index.cshtml
- Shared
- _LogOnPartial.cshtml
- Account
- Global.asax.cs
Here are the contents of each file (minus namespace stuff):
// AccountController.cs
public class AccountController : Controller
{
[HttpPost]
public ActionResult LogOn(LogOnModel model)
{
return View(model);
}
}// HomeController.cs
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}// AccountModels.cs
public class LogOnModel
{
[Display(Name = "User name")]
public string UserName { get; set; }
}@model MvcApplication6.Models.LogOnModel
I am LogOn.cshtml@{
Layout = "";
}
<html>
<head><title>I am Index.cshtml</title></head>
<body>
@Html.Partial("_LogOnPartial")
</body>
</html><!-- _LogOnPartial.cshtml -->
@model MvcApplication6.Models.LogOnModel@using (Html.BeginForm("LogOn", "Account"))
{
@Html.LabelFor(m => m.UserName)
@Html.TextBoxFor(m => m.UserName)
<input type="submit" value="Log On" />
}// Global.asax.cs
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
RouteTable.Routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}Click the "Log On" button and you will be redirected from http://localhost:56736/ to http://localhost:56736/Account/LogOn (the port will be di
- Controllers
-
Here are some thoughts to promote reusability: Consider a Facebook page that has 3 sections: - Your friends status updates - Friendship suggestions - Chat Rather than thinking of construction this page from one controller, think of more than one, for example: - Controller responsible for all updates - Controller responsible for all suggestions - Controller responsible for chat - Controller responsible on rendering a page (like the home page) The idea is that, the main view, like the home page, will be able to construct itself by "mixing and matching" what it needs to display from different controllers, in partial views or JSON format, using front-end frameworks e.g. jQuery maybe with conjunction with an MVVM framework like Knockout.js. Advantages: 1 - A controller will be serving a unique business case 2 - There is less dependencies in each controller, so a controller won't rely on the "UpdatesService", "SuggestionsService" and "ChatService" but will rely on smaller set of dependencies which promotes decoupling. 3 - You could change your controllers into RESTfull API services with less effort. 4 - An action method can be reused as it is doing a small and specific job. Disadvantages: 1 - Pushing more power to the JavaScript and the browser (that disadvantage might vary depending on your audience). 2 - More sophisticated JavaScript while JavaScript is not as mature as C# (unit testing frameworks for JS are not main stream yet, intellisense support is flaky (even with the latest Resharper), compile time checking doesn't exist, cross-browsers compatibility, etc...). 3 - A change in the controller affects more than one page, that means wider regression testing scope. I hope this helps.
Make it simple, as simple as possible, but not simpler.
Sorry, that does not really help. Suppose one of those controllers (e.g., ChatController) needs to accept a postback when the user clicks a submit button (e.g., a "Send" button to send a message) and that the user does not have JavaScript. Which action method would you recommend that postback go to and what ActionResult would you suggest it return? And keep in mind that I don't want the URL to change and I don't want the page layout to be different when the response is sent back to the client.
-
B/c there's no escaping jQuery and its excellent client-side unobtrusive validation, you may as well go ahead and bite the bullet and go full-out jQueryUI (which appears to have consistent and well-thought-out styling). My perspective on MVC3 is that it's best to avoid its ASP.NET underpinnings unless absolutely necessary and using ASP.NET custom controls is nas-ty by all accounts. Regardless, in the web app world, we can run but Javascript will track us down and make us do its bidding but I'm not going back to that miserable, back-stabbing, sloppy-a$$ terd ASP.NET. No way, Jose! That said, I'm not real happy with Razor, either. I mean, MS already had C#, T4 and J(ava)script (already used for their VS project and item template code), but I guess the syntax wasn't fsckd-up enough and the VS Editor didn't choke on them enough. Sheez. :-) Robert W. McCall execNext.com DONE := "Lasting peace & happiness for *ALL* human beings."
bmac wrote:
I'm not real happy with Razor
I love Razor. What's not to love? Succinct. Recursive helper methods. Powerful section handling. It's awesome.
-
I for one wished I didn't invest the time I did learning MVC as I find myself back using web forms and the tried and tested ado.net classes. This was wasted time and money for me. There is always Web forms MVP which is the way I would go now.
I'm not sure what ADO.NET has to do with anything, but I've never heard of Web Forms MVP... I'll have to look into that.
-
Mvc resusable controles are not dependent on ajax. Use uihint attribute over the property on which the control is to be rendered. In uihint pass the partial view name. In view page use editorfor to render that property. The partial view will be rendered automaticaly. The property will act as model to that partial view so make sure the datatype of the property and the model of the view is same.
MVC controls are reusable so long as they don't require a postback (e.g., a submit button). That's the tricky bit.
-
Have you looked at the helper method called @HTML.Action("ActionName", "ControllerName")? You can embed those on your _Layout (i.e. master) page as well as other views. It doesn't change the URL and allows you to grab data it its own controller separately from the host page. I use it with good success.
-Brian Hall-
I don't think that would help with a postback.
-
I'm going to throw this into the ring and see where it lands, so no thrashing. I'm just now doing heavy research on MVC3 as well. And I'm very interested in re-usable controls in MVC. That is how we currently do it in web forms. BUT, the control is linked to the parent page through events. For example, I click "Save" on the control, and it fires an event that is registered on the parent, to execute a method and in the method it basically fire the "Save" method on the control, plus whatever actions it needs to do (hide panels, display things, whatever) on the parent. ANYHOO, is there no way to register events like this between Views? Or is that the AJAX part everyone keeps mentioning? Personally, I agree with the OP and tend to avoid JavaScript whenever possible because the user can turn it off, and then you have a failed app.
EngleA wrote:
ANYHOO, is there no way to register events like this between Views?
One might be able to build something (e.g., have buttons submit a particular value and each "control"/partial view would look for that value in the request and would call a method accordingly), but there's nothing built-in to MVC to handle that. Not to mention that seems to bind the views and controllers a bit too closely.
-
EngleA wrote:
ANYHOO, is there no way to register events like this between Views?
One might be able to build something (e.g., have buttons submit a particular value and each "control"/partial view would look for that value in the request and would call a method accordingly), but there's nothing built-in to MVC to handle that. Not to mention that seems to bind the views and controllers a bit too closely.
And that's why I believe MVC3 is just not...enterprise ready. It's great for a personal blog or a music store (as long as no purchases are being made), but for an enterprise environment with business models and whatnot... I'll stick with ASP.NET and all it's random "clunkyness" because at least my code is re-usable, and I can link it up with WCF services and other products. :-D
-
Not exactly. You see, the reusability can be created only with the help of AJAX. In web forms, my user control need not rely on AJAX to be reusable. In MVC, the user control would simply fail completely without AJAX. Though, it's not too much to expect for a user to have JavaScript, so that's probably the route I'll take.
It seems that JavaScript is required for most web frameworks nowadays. In my opinion, that's a good thing. It makes a lot more sense for controls to work this way, and the overall behaviour of a page seems to be a lot more in the developer's control than with the old model.
-
OK, deliberately polemic/provocative title ;) . ASP.NET is really a semi-coercion of Winforms type development into a web context. Quite often it fights the web paradigm and hides stuff from the developer, in some cases this is a good thing, but in others it isn't. I know I've learnt more about the web part of web development more in the few months I've been using MVC3 than in a good few years of ASP.NET "Forms".
AspDotNetDev wrote:
After reading an 800-page book on MVC and just now starting to get my hands dirty, I still have seen no clear way to make reusable user controls in MVC.
My emphasis is important here. We've just spent the last x years (in my case 10, on and off) in the same way of working: "winforms" (For want of a better way of putting it) but across a client server architecture. MVC3 requires time to get to grips with, it is a different way of working (and much more harmoniously with http). Obviously the learning curve is there, and you'll spend a lot of time thinking in ASP.NET "Forms" I could just do x,y or z. Obviously this is because you've got the x years experience in ASP.NET, but less than one in MVC3. I know this as I had exactly the same thoughts when I started using MVC3 last summer. Now I prefer it for sites that aren't just "Winforms type Web apps", and even on those I'm increasingly 50:50 about. I seriously suggest you spend the time to get to know MVC3 Properly, I think it is really fantastic, when applied to the correct things. To look at your specific point about controls, let's say you want to create the Equivalent of an "Address Control": 1. Use the MVVM pattern, don't try and bind the business model directly unless it is a very good fit. The idea is to "bind" the [View]Model to the UI, by providing templates Dependency Injection becomes a breeze too. 2. Create an
AddressViewModel
class and any converters from the business model you want. 3. In the relevant folder (possibly views/shared) Create two folders "DisplayTemplates" and "EditorTemplates". These must be called this by convention to these add your markup in files calledAddress.cshtml
(assuming razor view engine). 4. Let's suppose you put the Address object you want to display in a parent View-Modelunder the a property calledCustomerAddress
. 5. Where you want to display the Address you just put@Html.DisplayFor(model => model.CustomerAddress)
editing is pretty much the same:Keith Barrow wrote:
Now I've used it for a few months, the thing that I find most objectionable about MVC3 is the amount of "Magic" that happens. A lot of stuff "just works" due to the reliance on convention and it feels like a chicken has been sacrificed and its bones cast to achieve it (The "postback" being "bound" the ViewModel in the example above, or individual form elements "just work" ).
Amen! I felt the same way after finishing the MVC Music Store Tutorial[^]. I'm starting to work through the book Professional ASP.NET MVC 3 from Wrox and I also have Programming Microsoft ASP.NET MVC 2nd Edition from Microsoft Press. I feel a bit lost still, but I think I'm starting to wrap my brain around the concepts... somewhat.... :-\ A 5 for the post. It's very informative. I'm sure I'll have a ton of questions as I go. Flynn
_If we can't corrupt the youth of today,
the adults of tomorrow will be no fun...
_ -
Sorry, that does not really help. Suppose one of those controllers (e.g., ChatController) needs to accept a postback when the user clicks a submit button (e.g., a "Send" button to send a message) and that the user does not have JavaScript. Which action method would you recommend that postback go to and what ActionResult would you suggest it return? And keep in mind that I don't want the URL to change and I don't want the page layout to be different when the response is sent back to the client.
-
dave.dolan wrote:
The url doesn't change.
Yes it does. Here, I'll give you an example. Suppose I create a new MVC 3 Internet project and delete most of the files. The remaining (important) files/folders are this:
- Controllers
- AccountController.cs
- HomeController.cs
- Models
- AccountModels.cs
- Views
- Account
- LogOn.cshtml
- Home
- Index.cshtml
- Shared
- _LogOnPartial.cshtml
- Account
- Global.asax.cs
Here are the contents of each file (minus namespace stuff):
// AccountController.cs
public class AccountController : Controller
{
[HttpPost]
public ActionResult LogOn(LogOnModel model)
{
return View(model);
}
}// HomeController.cs
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}// AccountModels.cs
public class LogOnModel
{
[Display(Name = "User name")]
public string UserName { get; set; }
}@model MvcApplication6.Models.LogOnModel
I am LogOn.cshtml@{
Layout = "";
}
<html>
<head><title>I am Index.cshtml</title></head>
<body>
@Html.Partial("_LogOnPartial")
</body>
</html><!-- _LogOnPartial.cshtml -->
@model MvcApplication6.Models.LogOnModel@using (Html.BeginForm("LogOn", "Account"))
{
@Html.LabelFor(m => m.UserName)
@Html.TextBoxFor(m => m.UserName)
<input type="submit" value="Log On" />
}// Global.asax.cs
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
RouteTable.Routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}Click the "Log On" button and you will be redirected from http://localhost:56736/ to http://localhost:56736/Account/LogOn (the port will be di
I see what you mean now about the redirect now. I have used MVC on many projects since 1.0 but they've all been either windows auth or no-auth so I hadn't noticed. (I know that's a red flag right there, someone just said 'enterprise.' After having my arse handed to me above I think I might deserve it.)
AspDotNetDev wrote:
So then, what haven't I figured out that you have?
That was not directed to you. I know I shouldn't mash it in with a reply to you. I generally regard you as a very intelligent person and I respect your posts. Sometimes I get carried away. (But you did too in the OP title. :P)
- Controllers
-
I see what you mean now about the redirect now. I have used MVC on many projects since 1.0 but they've all been either windows auth or no-auth so I hadn't noticed. (I know that's a red flag right there, someone just said 'enterprise.' After having my arse handed to me above I think I might deserve it.)
AspDotNetDev wrote:
So then, what haven't I figured out that you have?
That was not directed to you. I know I shouldn't mash it in with a reply to you. I generally regard you as a very intelligent person and I respect your posts. Sometimes I get carried away. (But you did too in the OP title. :P)
dave.dolan wrote:
But you did too in the OP title
The Lounge has been pretty boring lately. Thought I'd spice things up a bit. :rolleyes:
-
After reading an 800-page book on MVC and just now starting to get my hands dirty, I still have seen no clear way to make reusable user controls in MVC. Sure, one can create a partial view and use some AJAX so that the view can update itself by calling the appropriate controller/action. But if the user doesn't have JavaScript enabled, they're screwed. And I could pass around the main view name to the partial view, but then I'm either passing more details than I'd like to the client or I'm using session, which is best to avoid in a server farm situation (not to mention instantiating the proper model could prove troublesome). And I could have the partial view post to an action method on the parent view's controller, but then I have to do that for every page that makes use of the partial view. What a nightmare. I think I'll go back to ASP.NET web forms. :|
Imo this style of doing webapps is so yesterday. Use something like qooxdoo, ext, smartclient or sproutcore for the UI (all of which are great at letting you build reusable controls), and build your server-side app so it only supports stateless JSON-RPC requests. You trade some startup latency for almost no session info (you usually still have to keep auth info in the session, but that's about it - and you can consider it immutable, usually), lower bandwidth requirements and much lower latency. Plus, switching from one backend to another is a lot easier - presentation is separated at protocol level instead of API level, and there's no presentation code in your server app. And you get a services interface to your app for free - it's not just your web UI who can call the JSON-RPC services.