ASP.NET MVC: For Those Who Dislike Reusability
-
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 ...
-
-
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.
The problem with what you want is a matter of real estate. There is little room to show validation results without popping up another window. By going to the login page when there is an error, the user can either correct their input and submit, or register an account if they don't have one. This is how it work on The Code Project. However, if you want it your way, you would need to modify the Logon method, or create a similar one that redirects on errors as well as successful login. It would need to populate the ModelState errors collection and place values for UserName, Passwordm and redirectUrl in the ViewData or ViewBag. Additionally, you would need to modify the _LogonPartial.cshtml to include the validation stuff similar to the Logon.cshtml page. The ViewData or ViewBag is a great place to put data that might be needed by multiple pages, but really doesn't belong in the View's Model. Matthew Dennis Senior Architect The CodeProject
-
The problem with what you want is a matter of real estate. There is little room to show validation results without popping up another window. By going to the login page when there is an error, the user can either correct their input and submit, or register an account if they don't have one. This is how it work on The Code Project. However, if you want it your way, you would need to modify the Logon method, or create a similar one that redirects on errors as well as successful login. It would need to populate the ModelState errors collection and place values for UserName, Passwordm and redirectUrl in the ViewData or ViewBag. Additionally, you would need to modify the _LogonPartial.cshtml to include the validation stuff similar to the Logon.cshtml page. The ViewData or ViewBag is a great place to put data that might be needed by multiple pages, but really doesn't belong in the View's Model. Matthew Dennis Senior Architect The CodeProject
Matthew Dennis wrote:
The problem with what you want is a matter of real estate.
Perhaps on Code Project, but humor me would you. :)
Matthew Dennis wrote:
create a similar one that redirects on errors as well as successful login
So, create a response that asks the client to make another request to serve up another response? I just puked in my mouth a little bit. I think I'll just stick with the AJAX technique. :) Thanks for trying to help, but really MVC is not built to handle this type of modularity out of the box. :sigh:
-
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 ...
BobJanova wrote:
I think Keith has got the correct solution for you already.
I'm not so sure about that (and your solution doesn't seem to apply either). And don't worry, I'll stick with MVC despite its flaws. It's just too darn powerful otherwise. :)
-
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.
I don't know the structure of your home page, but consider this.. You can have an "index" action that returns an "home" view.. the index view can cointains a "render partial" for your login control. As long as any partial has an "isolated" form (nested forms are obviously not supported), you can actually make it post to any specific controller/action, posting only the values effectively required for the specific action. From that action, for example "AccountController/Login", you return as result a RedirectToAction to "HomeController/Index" (or you could resend the user to the last request url). You could pass an optional "LoginResult" in your ViewData or ViewBag, and use it in the "login Partial" to check if the user is logged and/or display a message if login failed. I hope that it can give you my opinion about reusability of mvc actions. In this way, you can have a login form in wherever you want.. it will always post to the same actions, which will just have to set a ViewData and redirect you to referrer url. Hope this can help
-
I don't know the structure of your home page, but consider this.. You can have an "index" action that returns an "home" view.. the index view can cointains a "render partial" for your login control. As long as any partial has an "isolated" form (nested forms are obviously not supported), you can actually make it post to any specific controller/action, posting only the values effectively required for the specific action. From that action, for example "AccountController/Login", you return as result a RedirectToAction to "HomeController/Index" (or you could resend the user to the last request url). You could pass an optional "LoginResult" in your ViewData or ViewBag, and use it in the "login Partial" to check if the user is logged and/or display a message if login failed. I hope that it can give you my opinion about reusability of mvc actions. In this way, you can have a login form in wherever you want.. it will always post to the same actions, which will just have to set a ViewData and redirect you to referrer url. Hope this can help
I'm afraid that was already suggested, and I already replied. Thanks for trying to help though. :)
-
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. :|
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.
-
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. :|
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."
-
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.
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.
-
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.