ASP.NET MVC: For Those Who Dislike Reusability
-
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. :|
-
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. :|
Oh, and another thing;
AspDotNetDev wrote:
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.
Is that not the same regardless what technology you use?
Dave Find Me On: Web|Facebook|Twitter|LinkedIn
Folding Stats: Team CodeProject
-
Oh, and another thing;
AspDotNetDev wrote:
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.
Is that not the same regardless what technology you use?
Dave Find Me On: Web|Facebook|Twitter|LinkedIn
Folding Stats: Team CodeProject
I assume he's talking about on post-back.
cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP
-
I find it extremely hard to believe you can do something in webforms, but cannot do the comparable task in MVC.
Dave Find Me On: Web|Facebook|Twitter|LinkedIn
Folding Stats: Team CodeProject
Me too, Dave, me too. But the thing is that it can be done, with your pick of caveats. For one, you could use AJAX, and it'd work dandy. Or, you could put the burden of implementation on the controller of the page that is using the partial view (though the the action method could call back to some other central code to handle most of the processing). I love most of MVC and think it's a fantastic improvement over web forms... just this little bit (which is actually kind of a big bit) is not quite ideal.
-
Oh, and another thing;
AspDotNetDev wrote:
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.
Is that not the same regardless what technology you use?
Dave Find Me On: Web|Facebook|Twitter|LinkedIn
Folding Stats: Team CodeProject
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.
-
I assume he's talking about on post-back.
cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP
Indeed. Partial views are completely reusable if they do not require postback. It is when a postback is involved that things fall apart (a topic of which pretty much everything I've read to date has simply avoided).
-
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. :|
My impression of "ASP.NET MVC" has always been that it is the epitome of that style of programming in which one is expected to blindly do things a certain way, over and over again, without question. The sort of people who this sort of thing appeals to are those who are admirably concerned with following good patterns and practices, but less concerned about the speed or nature of what they're actually doing. Within the little clique of people who adhere to ASP.NET MVC, you will be chided for not following the pattern. The environment will not be criticized for giving you the opportunity to mess up. It's the developer's fault (according to what seems to me to be their perspective). As you might imagine, you will find yourself doing a lot of reading, watching videos, etc., if you elect to use ASP.NET MVC.
-
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. :|
It's been a while, but can't you use RenderPartial("ViewName") and have the view in a central location? The actions in the partial view would refer to the calling controller. I've also used the same view with different controllers. No AJAX involved. I don't see the problem.
If your actions inspire others to dream more, learn more, do more and become more, you are a leader." - John Quincy Adams
You must accept one of two basic premises: Either we are alone in the universe, or we are not alone in the universe. And either way, the implications are staggering” - Wernher von Braun -
It's been a while, but can't you use RenderPartial("ViewName") and have the view in a central location? The actions in the partial view would refer to the calling controller. I've also used the same view with different controllers. No AJAX involved. I don't see the problem.
If your actions inspire others to dream more, learn more, do more and become more, you are a leader." - John Quincy Adams
You must accept one of two basic premises: Either we are alone in the universe, or we are not alone in the universe. And either way, the implications are staggering” - Wernher von BraunSee here. The problem arises when you need a partial view to perform a postback.
ahmed zahmed wrote:
The actions in the partial view would refer to the calling controller
That is the third scenario I outlined. Why should the calling controller have to reimplement every action method called by the partial view? For example, say I have a login control on a layout view (whatever they're called... the view in MVC that acts like a masterpage would in web forms). It has username/password fields on it and a button (like the one on the top of the page for Code Project when you are not logged in). When you click the button, it might call the "LogIn" action method. That action method would have to reside on any controller that is used by a view that has the partial view. And supposing you have several partial views on your pages, all the action methods referred to by them would need to reside on the calling controllers. That is a PITA if you ask me.
-
My impression of "ASP.NET MVC" has always been that it is the epitome of that style of programming in which one is expected to blindly do things a certain way, over and over again, without question. The sort of people who this sort of thing appeals to are those who are admirably concerned with following good patterns and practices, but less concerned about the speed or nature of what they're actually doing. Within the little clique of people who adhere to ASP.NET MVC, you will be chided for not following the pattern. The environment will not be criticized for giving you the opportunity to mess up. It's the developer's fault (according to what seems to me to be their perspective). As you might imagine, you will find yourself doing a lot of reading, watching videos, etc., if you elect to use ASP.NET MVC.
I'm screwed then. I'm just hacking it together based on having a problem to solve. Why do I get the feeling that there's a huge boot waiting to kick me?
*pre-emptive celebratory nipple tassle jiggle* - Sean Ewington
"Mind bleach! Send me mind bleach!" - Nagy Vilmos
CodeStash - Online Snippet Management | My blog | MoXAML PowerToys | Mole 2010 - debugging made easier
-
See here. The problem arises when you need a partial view to perform a postback.
ahmed zahmed wrote:
The actions in the partial view would refer to the calling controller
That is the third scenario I outlined. Why should the calling controller have to reimplement every action method called by the partial view? For example, say I have a login control on a layout view (whatever they're called... the view in MVC that acts like a masterpage would in web forms). It has username/password fields on it and a button (like the one on the top of the page for Code Project when you are not logged in). When you click the button, it might call the "LogIn" action method. That action method would have to reside on any controller that is used by a view that has the partial view. And supposing you have several partial views on your pages, all the action methods referred to by them would need to reside on the calling controllers. That is a PITA if you ask me.
In the action links though you could specify the controller, same way as you handle MVC areas or pass in additional routing values. eg. actionlink("Do Something", "doSomething", new {controller = "AController" [, id="5", area="AnArea"]}) would that not help? You could also possibly pass in a specific attribute to determine which postback you were trying to handle on that page.
Dave Find Me On: Web|Facebook|Twitter|LinkedIn
Folding Stats: Team CodeProject
-
My impression of "ASP.NET MVC" has always been that it is the epitome of that style of programming in which one is expected to blindly do things a certain way, over and over again, without question. The sort of people who this sort of thing appeals to are those who are admirably concerned with following good patterns and practices, but less concerned about the speed or nature of what they're actually doing. Within the little clique of people who adhere to ASP.NET MVC, you will be chided for not following the pattern. The environment will not be criticized for giving you the opportunity to mess up. It's the developer's fault (according to what seems to me to be their perspective). As you might imagine, you will find yourself doing a lot of reading, watching videos, etc., if you elect to use ASP.NET MVC.
_beauw_ wrote:
you will find yourself doing a lot of reading, watching videos, etc
I have finished reading Pro ASP.NET MVC 3 Framework and it goes over the various aspects of MVC 3 with a good amount of detail. However, I'm hoping to find a book that is basically about doing practical things, like building user controls. After looking at some books on Amazon, I didn't come across any that cover this topic in any sort of detail. I suspect I'm just going to have to pick among the less than ideal options I have come up with, and wait for a couple more versions of MVC to come out before a best practice is devised (and incorporated into books and and other resources).
-
In the action links though you could specify the controller, same way as you handle MVC areas or pass in additional routing values. eg. actionlink("Do Something", "doSomething", new {controller = "AController" [, id="5", area="AnArea"]}) would that not help? You could also possibly pass in a specific attribute to determine which postback you were trying to handle on that page.
Dave Find Me On: Web|Facebook|Twitter|LinkedIn
Folding Stats: Team CodeProject
I don't follow exactly. I'll assume you are talking about the situation without AJAX. What I'd do on my partial view is have a form which submits to a particular controller/action specific to that partial view (say, the LogIn action on the Account controller). The problem is that that LogIn action would have to return a view. If it returns a the partial view, the URL changes (to, say, site.com/Account/LogIn). Now, if I were to pass in the name of the parent view to the partial view, I could use the overload of the View method that accepts the view name. So I could return View("~/Views/Home/Index.cshtml"), but then I couldn't really pass it a model, as the only model I have access to in the LogIn action is the model for that specific task rather than the entire model for the Home.Index action. Not to mention all this passing around of view locations makes me nervous (I don't want the client being able to hack the postback to specify their own view, and I don't want to store that in session, as that screws up a load balanced architecture if every user control needs to use the session). There are ways of getting around this. For example, the view name passed to the client could be encrypted. However, I'm then basically recreating web forms from scratch.
-
See here. The problem arises when you need a partial view to perform a postback.
ahmed zahmed wrote:
The actions in the partial view would refer to the calling controller
That is the third scenario I outlined. Why should the calling controller have to reimplement every action method called by the partial view? For example, say I have a login control on a layout view (whatever they're called... the view in MVC that acts like a masterpage would in web forms). It has username/password fields on it and a button (like the one on the top of the page for Code Project when you are not logged in). When you click the button, it might call the "LogIn" action method. That action method would have to reside on any controller that is used by a view that has the partial view. And supposing you have several partial views on your pages, all the action methods referred to by them would need to reside on the calling controllers. That is a PITA if you ask me.
So if I understand correctly, you want to be able to "add widget" in multiple places? There are several mechanisms to handle that. You could use inheritance (ok when there's only a single instance of reuse in the target) not so good if there are multiple partial views. Here's a case where multiple inheritance might be useful. You could use helper classes that are associated with the partial view and forward the action callback to those helper classes. Also, I think there's a way to specify that a particular postback go to a particular controller's action.
If your actions inspire others to dream more, learn more, do more and become more, you are a leader." - John Quincy Adams
You must accept one of two basic premises: Either we are alone in the universe, or we are not alone in the universe. And either way, the implications are staggering” - Wernher von Braun -
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. :|
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
-
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
-
I'm screwed then. I'm just hacking it together based on having a problem to solve. Why do I get the feeling that there's a huge boot waiting to kick me?
*pre-emptive celebratory nipple tassle jiggle* - Sean Ewington
"Mind bleach! Send me mind bleach!" - Nagy Vilmos
CodeStash - Online Snippet Management | My blog | MoXAML PowerToys | Mole 2010 - debugging made easier
Well, I'm just conveying my general impression, as someone who used to use WebForms and who likes to read about software development. Unfortunately, this general impression is that ASP.NET MVC just doesn't lend itself to the approach you described ("just hacking it together based on having a problem to solve").
-
Well, I'm just conveying my general impression, as someone who used to use WebForms and who likes to read about software development. Unfortunately, this general impression is that ASP.NET MVC just doesn't lend itself to the approach you described ("just hacking it together based on having a problem to solve").
It's working well enough for me at the moment - mind you, I've used MVC/MVP/MVVM patterns for years so I'm used to working in that way.
*pre-emptive celebratory nipple tassle jiggle* - Sean Ewington
"Mind bleach! Send me mind bleach!" - Nagy Vilmos
CodeStash - Online Snippet Management | My blog | MoXAML PowerToys | Mole 2010 - debugging made easier
-
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
All of that was covered in the book I read (with the possible exception of code generation templates, though those don't really apply to the scenario I have in mind).
Matthew Dennis wrote:
MVC supports re-use of UI in varioius ways
What I'm basically talking about is reuse of behavior. If you really think you can provide some input (which I would love, but I suspect that MVC is not well built for what I'm after), see my question I posted yesterday, Return Current View From Different Controller (MVC Log On Control). I've had some time to think and that doesn't really explain as clearly as I'd like what I'm trying to accomplish, so I'll give you a concrete example here from Code Project. At the top of every page on Code Project, there is a login control. When I am logged in, it shows my username. When I am logged out, it shows two input fields (Email and Password) and a submit button, "Sign In". If I enter an invalid password and click Sign In, I am redirected to http://www.codeproject.com/script/Membership/LogOn.aspx. That's not what I want in my scenario. What'd I'd like is for a postback to take place (not an AJAX postback), for the validation to find that my credentials are invalid, and for me to be shown the page I was on when I clicked Sign In (say, the homepage... http://www.codeproject.com/), but with a message indicating that my credentials are invalid. And since this user control is on every single page on Code Project, I'd rather not have to implement the "SignIn" action on every single controller (HomeController, ForumController, ArticleController, SurveyController, QuestionController, MvpController, and so on). Though if I did have to do that, I realize that I could put the majority of the logic in some central location, and call that logic from each SignIn action. Still, that reqires that I duplicate that method essentially everywhere. That is especially cumbersome when I have my Code Project login control on a layout that is used by all the views. Then the views don't even necessarily know what is in the layout view... so they must somehow divine that such an action method is necessary and then go through the work of implementing it. That does not sound very clean to me, and it opens up the possibility that some
-
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. :|
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: