ASP.NET MVC: For Those Who Dislike Reusability
-
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").
Works well for me. I'm quicker in MVC3 after a few months, and I've been using ASP.NET from within a few months of v1.0 coming out. I get that benfit, and the code is cleaner by virtue of following the MVC3 pattern. Or more correctly it forces me into the discipline of keeping everything in the right place, which leads to the productivity gain, sometimes those "academic" patterns are good. That said, you've got to get your head around it first.
Sort of a cross between Lawrence of Arabia and Dilbert.[^]
-Or-
A Dead ringer for Kate Winslett[^] -
Keith Barrow wrote:
That said: I used to think WPF was the future of Winforms development
I forgot to say, I friggin love WPF. Definitely didn't encounter any reusability problems when working with it (it's only flaws that I saw were the steep learning curve and the occassional Visual Studio bug). :)
WPF + MVVM isn't a huge step from MVC3 + MVVM! The actual binding/GUI is different, but my experience with it helped a lot with MVC3 (I had one GUI that had only three method in the front end, two were for error handling and the other was setting up interop with c++ app. Everything was type-templated and run from the view model with DI. A well written MVC3 app would be pretty similar (need to play with DI properly) though I've yet to get that zen-like glow with MVC3.
Sort of a cross between Lawrence of Arabia and Dilbert.[^]
-Or-
A Dead ringer for Kate Winslett[^] -
Hmmm, that may be workable, but my knowledge of display templates is only theoretical, as I've not had a chance to actually implement one. I'll give it a try, though trying to imagine how this would be done brings up some questions. For example, this means I'd have to have an AddressViewModel property on every model that is used by a "page" (or view... or whatever) that makes use of the address functionality, right? And this editor "control" doesn't have it's own controller (or am I wrong about that?), so any logic to manipulate the data will have to be done by each "page" controller, right? So, say somebody edits the address and clicks "submit" on some page... that submit button would probably call on the action method for that page (say, Home/Index) and that action method would need to check if the address was changed and, if so, persist it (say, to a database). If all that is true, it doesn't seem like it's cutting down on the code any.
A display template is only a partial view (with a defined model type, in the DisplayTemplates folder, named after the class it is designed to display :)). Getting one going was a big step forward for me.
AspDotNetDev wrote:
For example, this means I'd have to have an AddressViewModel property on every model that is used by a "page" (or view... or whatever) that makes use of the address functionality, right?
Right.
AspDotNetDev wrote:
And this editor "control" doesn't have it's own controller (or am I wrong about that?)
It doesn't, but you could put it into its own html form and point that at a single method on a specific if you want to. Obviously which you go for depends on what you need.
AspDotNetDev wrote:
so any logic to manipulate the data will have to be done by each "page" controller, right?
Yes and no. You can do this, but again, this is dependant on what you want to do. You could have a single method on one controller (in my answer to your Login question in Q&A, this is the case). Though you could have the method on each controller if you wanted. Don't forget you can subclass a base controller if you don't want to repeat code.
Sort of a cross between Lawrence of Arabia and Dilbert.[^]
-Or-
A Dead ringer for Kate Winslett[^] -
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
Pete O'Hanlon wrote:
Why do I get the feeling that there's a huge boot waiting to kick me?
Because you know me, that's why. Lucky for you, I haven't been able to afford a ticket to fly to Pommyland to deliver said kick from the huge boot.
Michael Martin Australia "I controlled my laughter and simple said "No,I am very busy,so I can't write any code for you". The moment they heard this all the smiling face turned into a sad looking face and one of them farted. So I had to leave the place as soon as possible." - Mr.Prakash One Fine Saturday. 24/04/2004
-
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.
That is incorrect. The HTML that is rendered could/should be in the _layout.cshtml or MasterPage, depending if you are using Razor or ASP.NET as your View Engine. It would be enclosed in a
tag (MVC allows more than on form per View) and would post to a single Account Controller. This is how it is done in the default VS template for MVC 2 and 3. MVC 4 uses AJAX or a Form Post allowing enhanced experience if JavaScript is available. To put it another way. A View (Page) can have multiple forms, each of which can Post to different Controllers and/or methods. This makes if very easy to create UI widgets. Matthew Dennis
-
That is incorrect. The HTML that is rendered could/should be in the _layout.cshtml or MasterPage, depending if you are using Razor or ASP.NET as your View Engine. It would be enclosed in a
tag (MVC allows more than on form per View) and would post to a single Account Controller. This is how it is done in the default VS template for MVC 2 and 3. MVC 4 uses AJAX or a Form Post allowing enhanced experience if JavaScript is available. To put it another way. A View (Page) can have multiple forms, each of which can Post to different Controllers and/or methods. This makes if very easy to create UI widgets. Matthew Dennis
Matthew Dennis wrote:
A View (Page) can have multiple forms, each of which can Post to different Controllers and/or methods.
But once they post to that controller action method, that action method must return an ActionResult, one of which is a ViewResult (the usual return value). How would my LogOn action method know to return the ~/Views/Home/Index.cshtml view? If it just returns its own view (~/Views/Account/LogOn.cshtml), then the user will see that view rather than the view for the page they posted from.
Matthew Dennis wrote:
This is how it is done in the default VS template for MVC 2 and 3.
The MVC 3 Internet project is the one I started from. It has the LogOn as its own page, rather than an embedded control on each page (and it has another control on the top of each page that links to the LogOn page). That is not what I consider a widget.
-
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
I think you will get the functionality you want if you modify the \Views\Shared\_LogOnPartial.cshtml to look like the following code. I haven't done any styling but it works. The partial renders a form which posts to
AcccountController.Logon
. I started with the default MVC 3 Internet App VS template.@if(Request.IsAuthenticated) {
Welcome @User.Identity.Name!
[ @Html.ActionLink("Log Off", "LogOff", "Account") ]
}
else {
using (Html.BeginForm("Logon", "Account"))
{@Html.Label("Name:") @Html.TextBox("UserName") @Html.Label("Password:") @Html.Password("Password") @Html.CheckBox("RememberMe") @Html.Label("Remember Me") <input type="submit" value="Login" /> <input type="hidden" name="returnUrl" value="@Request.Url.PathAndQuery" /> }
}
-
Matthew Dennis wrote:
A View (Page) can have multiple forms, each of which can Post to different Controllers and/or methods.
But once they post to that controller action method, that action method must return an ActionResult, one of which is a ViewResult (the usual return value). How would my LogOn action method know to return the ~/Views/Home/Index.cshtml view? If it just returns its own view (~/Views/Account/LogOn.cshtml), then the user will see that view rather than the view for the page they posted from.
Matthew Dennis wrote:
This is how it is done in the default VS template for MVC 2 and 3.
The MVC 3 Internet project is the one I started from. It has the LogOn as its own page, rather than an embedded control on each page (and it has another control on the top of each page that links to the LogOn page). That is not what I consider a widget.
See my Reply with example[^]
-
I think you will get the functionality you want if you modify the \Views\Shared\_LogOnPartial.cshtml to look like the following code. I haven't done any styling but it works. The partial renders a form which posts to
AcccountController.Logon
. I started with the default MVC 3 Internet App VS template.@if(Request.IsAuthenticated) {
Welcome @User.Identity.Name!
[ @Html.ActionLink("Log Off", "LogOff", "Account") ]
}
else {
using (Html.BeginForm("Logon", "Account"))
{@Html.Label("Name:") @Html.TextBox("UserName") @Html.Label("Password:") @Html.Password("Password") @Html.CheckBox("RememberMe") @Html.Label("Remember Me") <input type="submit" value="Login" /> <input type="hidden" name="returnUrl" value="@Request.Url.PathAndQuery" /> }
}
Nope. When I filled in a fake name/password and clicked "Login", I was redirected to http://localhost:61526/Account/Logon. What I want is, when I click "Login", I stay on http://localhost:61526/ and get a validation summary right on the page rather than being redirected to a page dedicated to logging in.
-
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. :|
Which book?
Will Rogers never met me.
-
Which book?
Will Rogers never met me.
-
Ah, I see. I was just curious, since last year I reviewed a book on MVC 3 for Manning. I understand that the book was never published because MS introduced MVC 4 before it was done, but the authors have revised and released it for the newer version.
Will Rogers never met me.
-
Ah, I see. I was just curious, since last year I reviewed a book on MVC 3 for Manning. I understand that the book was never published because MS introduced MVC 4 before it was done, but the authors have revised and released it for the newer version.
Will Rogers never met me.
I have a few MVC 4 books that are not yet released in my Amazon wish list. If you let me know which you reviewed (in its MVC 3 incarnation), I'd give that one priority :-)
-
I have a few MVC 4 books that are not yet released in my Amazon wish list. If you let me know which you reviewed (in its MVC 3 incarnation), I'd give that one priority :-)
I don't know for sure that it's been released yet, but I assume so. When I inquired about the MVC 3 book I was supposed to receive for reviewing it, I learned that it was superseded by the MVC 4 version, and received a pdf of that book. The title is "ASP.NET MVC 4 in Action, Third Edition" and it's offered by Manning Publications (www.manning.com). I haven't yet had time to read the new version, but I found the MVC 3 version to be very informative, and the examples used to be practical. That's fairly rare in the programming text world. It was also rather entertaining, in that the authors are obviously not native speakers of English, and the phrasing and diction were sometimes rather quaint. I didn't have any trouble at all reading it; more of a Balkan slant than Indian - I think they said that they're from Romania or somewhere nearby. I dunno... I found the original book quite useful and informative, and I expect the new version to be equally as useful. Since I'm not a web developer, my opinion is about as valuable as a bus token in an airport, but I liked the book. I suggested that they change a few terms - the authors used the term "hydrate" when the accepted term is "instantiate," for instance, and I think they made the change. I found it amusing, but not at all distracting, while reading the text. If it's available, and not too expensive, I'd give it a try. I'd send you a copy of the pdf version I have, knowing that you would buy a hard copy if you found it useful, but that would violate my agreement with them. Sorry about that, but I take those things seriously... :)
Will Rogers never met me.
-
I don't know for sure that it's been released yet, but I assume so. When I inquired about the MVC 3 book I was supposed to receive for reviewing it, I learned that it was superseded by the MVC 4 version, and received a pdf of that book. The title is "ASP.NET MVC 4 in Action, Third Edition" and it's offered by Manning Publications (www.manning.com). I haven't yet had time to read the new version, but I found the MVC 3 version to be very informative, and the examples used to be practical. That's fairly rare in the programming text world. It was also rather entertaining, in that the authors are obviously not native speakers of English, and the phrasing and diction were sometimes rather quaint. I didn't have any trouble at all reading it; more of a Balkan slant than Indian - I think they said that they're from Romania or somewhere nearby. I dunno... I found the original book quite useful and informative, and I expect the new version to be equally as useful. Since I'm not a web developer, my opinion is about as valuable as a bus token in an airport, but I liked the book. I suggested that they change a few terms - the authors used the term "hydrate" when the accepted term is "instantiate," for instance, and I think they made the change. I found it amusing, but not at all distracting, while reading the text. If it's available, and not too expensive, I'd give it a try. I'd send you a copy of the pdf version I have, knowing that you would buy a hard copy if you found it useful, but that would violate my agreement with them. Sorry about that, but I take those things seriously... :)
Will Rogers never met me.
I've got to say, I don't have high hopes. It's listed on Amazon as ASP.NET MVC 3 in Action even though the cover image shows it as "ASP.NET MVC 4 in Action". The book description on Amazon also says 3 instead of 4. :laugh:
-
I've got to say, I don't have high hopes. It's listed on Amazon as ASP.NET MVC 3 in Action even though the cover image shows it as "ASP.NET MVC 4 in Action". The book description on Amazon also says 3 instead of 4. :laugh:
Well, they're furriners... What can we expect? :-D
Will Rogers never met me.
-
Pete O'Hanlon wrote:
Why do I get the feeling that there's a huge boot waiting to kick me?
Because you know me, that's why. Lucky for you, I haven't been able to afford a ticket to fly to Pommyland to deliver said kick from the huge boot.
Michael Martin Australia "I controlled my laughter and simple said "No,I am very busy,so I can't write any code for you". The moment they heard this all the smiling face turned into a sad looking face and one of them farted. So I had to leave the place as soon as possible." - Mr.Prakash One Fine Saturday. 24/04/2004
Ahh yes. I'd forgotten the mutual ass-kicking contest; all because of a typo.
*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
-
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: -
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 think Keith has got the correct solution for you already. But, not knowing that, when I came across this problem I created some control classes which implemented an interface with one method – Render, which generated HTML. Then you can do
Response.Write(new PartialWhateverControl(Model.DataObject).Render());
... in the view. I think I'll go back to ASP.NET web forms. Noooooooooo ...
-