ASP.NET MVC: For Those Who Dislike Reusability
-
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 ...
-
-
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. :)