MVC - How to create a wrapper for Html.RenderPartial? - asp.net-mvc

I would like to either override or create a custom function to wrap the RenderPartial shared function found in System.Web.Mvc.Html RenderPartialExtensions.
I found an article talking about this idea here:
http://johncoder.com/Post/AdventuresinDebuggingAFriendlierCalltoRenderPartial
<% Html.TryRenderPartial("ClassB", Model.B); %>
In the example above, they have created a custom sub called TryRenderPartial that does some logic and calls RenderPartial if necessary. Unfortunately this article does not give a code example of the TryRenderPartial sub itself.
I can't figure out how to create this function because the RenderPartialExtensions is not inheritable. Also I'm not sure how to actually output the html because RenderPartial is a sub, not a function, so I don't get how to actually "return" the html. Any ideas?

It's literally trivial to wrap RenderPartial. You just create an HtmlHelper extension like so (in C#, I don't speak VB):
public static class MyRenderPartialExtensions
{
public static void MyRenderPartial(this HtmlHelper htmlHelper, string partialViewName)
{
htmlHelper.RenderPartial(partialViewName)
}
}
You would add similar methods for the other overloads you want to implement.
However, chances are, you probably don't really want to do this... most likely, what you want to do is already possible in a way that the framework exposes.
This is what's known as an XY Problem, which basically means that you have Problem X, and you have decided that you need to do Y to solve it. However, you can't figure out how to do solution Y, so you're asking how to do Y rather than asking how to do your original X problem.
The reason why XY problems are bad is because chances are, the solution you've decided you need to do is not the correct solution, and the reason you're having trouble with it is because it's not the right way to do things.
Frankly, I can't think of a good reason to wrap RenderPartial, since anything you'd do is more than likely doable in some other way.
To respond to your other comment, Html helpers don't "return" anything. That's why they're Sub's. How view rendering works is rather complex, and not a subject easily discussed in an SO answer.
HtmlHelpers don't work via inheritance, they use Extension Methods.
http://msdn.microsoft.com/en-us/library/bb384936.aspx

Related

what does the dollar do on $height of a UITextfield object?

I just got aware that there are some properties on objects of classes that have a dollar sign as prefix:
$height
$left
$origin
$size
... etc
I can use it as a setter e.g.
self.textField.$height = 44;
Q: how is this called, what is it good for and is it good practice to use is like this?
It seems that you are using category UIView+FrameAdditions.h.
More on categories here.
$ signs have no special meaning in this case - they are actually a bit unconventional to use in ObjC.
It is just a way developer named the helper methods in this category.
This $-prefix looks a bit strange but on the other hand it does help distinguish between native ObjC properties of UIView's frame and category helper methods.
Nick Farina (developer of this category) actually calls this as "kind of like jQuery for UIViews"
As for your question: is it a good practice to use it like this?
As said: $-sign is uncommon and i would ditch it personally. Especially if there is a chance that someone else will once work on the same project.
But the category itself can be very usefull and time-saving.

What is the use of Html.BeginForm in MVC3

What is the use of Html.BeginForm in MVC3.
Why do we use it, when we can just add a form tag directly, does this html helper add some capability or does something which cannot be done with a simple form tag.
The Html.BeginForm helper method contains a couple overloads whose intended purpose is to make writing routed forms easier. It is aware of MVC stucture and makes sure its targeting a controller and action. It's just a bit of syntactic sugar over:
<form method="post" action="#Url.Action(...)">
In Microsoft's words:
The ASP.NET MVC framework includes helper methods that provide an easy way to render HTML in a view.
Of course, no one is making you use them. Its just a matter of preference. In fact, in the early days of MVC, many WebForms developers celebrated their new freedom from server controls a-la <asp:TextBox> et al., and insisted on writing everything by hand.
Using the helpers for your form fields comes highly recommended, since they're aware of things like form validation. Html.BeginForm just gives you a consistent way to start and finish your form:
#using(Html.BeginForm())
{
#Html.LabelFor(...)
#Html.EditorFor(...)
}
Html.BeginForm returns an IDisposable object, allowing you to wrap it in the C# using statement. When the using exits, the disposal will call Html.EndForm() automatically for you. Since Html.EndForm returns void it is slightly inconvenient to call from Razor:
#Html.BeginForm()
<formStuff>
#{Html.EndForm();}
A simple #Html.EndForm() will turn in to Write(Html.EndForm()) -> Write(void), ie compile time error.
Of course you can code it by hand, but it does have several advantages, such as:
it returns an object that is disposable, so that you can put it in a using clause and it will close the form tag for you
it computes the URL for the form action
does something which cannot be done with a simple form
At the end every helper method call is converted to pure HTML so there is nothing that Html.BeginForm can do that can't be done by using the <form> tag directly.
Html.BeginForm is purely an helper method.
What's the purpose of having helpers at all? (Rhetorical question) You could type all inputs manually as well, but helpers... well, help you sometimes.
all it does it put tag. Yes, you can do it manually, or you can be a bit more fancy and do this:
#using(Html.BeginForm())
{
}
This will close the form tag for you as well. So if you keep all your inputs inside the curvy brackets, you don't need to worry about remembering closing the form tag.
Excellent question, I wondered about that myself quite a bit.
I could be wrong, but here's my guess (a better man may correct me):
In the early days of MVC, there was no razor.
Switching between C#/VB and html was hard syntax-wise, so there was a push towards minimizing those borders.
When creating forms, it was seen beneficial to create the entire form purely on the C#/VB side, without any intermingling manual html, to just have one border to the surrounding world of html.
And since programmers often copy the style of doing things from somewhere else, the practice of using those helpers has persisted even though their benefit has disappeared with the advent of razor.

ASP.NET MVC: When to use HTML helpers in views - Tidying up the code!

I am trying to refactor my views a bit and up til now i have been using the built HTML helpers but i thought i would create my own - they're extension methods right?
I wonder if anyone can confirm or give advise when an HTML is needed? I think i once saw a document that said if you use 1 IF statement in your views encapsulate it into a html helper - would anyone agree with that?
With regards to creating html helpers, would it be better to create my own class rather than add extension methods to the HTML class that ships with MVC? Any body have ideas on this?
Or possible i shouldn't bother with HTML helpers and just use the built in ones and continue to use my IF statements within views.
Thanks in advance
Use HTML helpers when you want to encapsulate the output of a piece of HTML markup that can take varying values.
I'd recommend creating them as extension methods to HtmlHelper rather than creating your own class, as your own class won't be available inside of the default ViewPage without either instantiating a new instance inside of the View or subclassing ViewPage and using this in the View (or passing in on the model, but that's just wrong!).
HTML Helpers are extension methods. I can confirm as well that I too use the 'if' rule when it comes to views. Any view logic coded should, IMO, be in a helper.
You can use helper to render custom markup, or control which markup(ie existing view) is displayed.
Not too sure about the ease of this, but it does lend itself to more unit testing (please comment on this aspect if someone has more info).
With regards to creating html helpers, would it be better to create my own class rather than add extension methods to the HTML class that ships with MVC? Any body have ideas on this?
If I understand correctly, in this respect my suggestion would to separate your helpers into their own classes. The reasoning behind this for me would be that you easily know when looking at your views what are standard helpers vs the ones you've created. I think this will improve maintainability.
i shouldn't bother with HTML helpers and just use the built in ones and continue to use my IF statements within views.
I'd say No! (or it depends). One of the benefits of using a helper would be to reuse the same view logic in multiple views as opposed to re-coding the same if statements. This means your code is more DRY, which is always better. In the event you need to debug some weirdness error, you only need to look in one place, the newly created helper.

Where to place the code for best practice?

I have an asp.net mvc application and I have a page for presenting meteo information. It looks like:
Temperature for today is 34-35 degrees
For this
34-35 degrees
, I have a method that assure that the text will be in format
[Number][Dot][Number]
called AssureCorrectDegressFormat().
Now I am asking where is it suited the best. Untill now I was calling it from the view, smth like this:
But as I think the view is intended only to display data , not to call some methods in order to operate with thise literals. I moved my class SafeData to the Core of my application, and I pass to the view the DTO that has already called this method and obtained the right data for displaying. I am interested in your opinions about this, where is the best place to put this class, maybe in Infrastructure layer and where to call it, now I call itr from my services . I forgot to say that I am using a DDD aproach.
Formatting, from my perspective, is a view-related function and so it should be called in the view. As to the code that actually does the formatting, I might create an HtmlHelper extension to handle the formatting. That way I could use it wherever I wanted, but have the code in only one place.
<%= Html.ShowDegrees( DV.TheDegreeString ) %>
Formatting the display of data in the View seems fine to me. You wouldn't think twice about about putting this on your View:
<%= Model.MyDate.ToString("f") %>
would you? The principal is the same.
If it's a very simple formatting or calculation, I just put it in the view. If it's any more complex than that, I will put a method in the ViewModel. If it is complex and can be used many places, I will create an HtmlHelper for it.

MVC Best Practices | Do you build your links into the Url Helper?

Just read a post about MVC best practices. Couple parts of the post described building helper methods to link to actions on the controllers. Here's a clip:
1) Create Extension methods of UrlHelper to generate your url from
Route
Avoid passing the controller, action
or route name as string, create
extension methods of UrlHelper which
encapsulates it, for example:
public static class UrlHelperExtension
{
public static string Home(this UrlHelper helper)
{
return helper.Content("~/");
}
public static string SignUp(this UrlHelper helper)
{
return helper.RouteUrl("Signup");
}
}
I can see how this would shorten links used in views... but I don't see how this is a "best practice". Perhaps I'm simply overlooking something. Should I be doing this to build my links? Are there benefits to this I'm just not seeing?
He even goes on to say that stylesheets, images, and javascript helpers should be made...
I probably wouldn't do this unless the route is referenced in multiple places. I can see the value in doing this, and I have implemented HtmlHelper extensions for adding style sheets and javascript includes to add the ability to use "versioned" links, but my common links are included as ActionLinks in a UserControl (menu) and for most other things I use either ActionLink or BeginForm/AjaxForm to reference the action. In some respects it feels like creating new methods for all but the most commonly reused links is adding complexity for very little value -- the kind of value that you would get from some simple manual testing of your UI, which you'd have to do anyway.
If you make a mistake when writing a URL as a string, it won't be caught until runtime. This way, attempting to refer to a route that hasn't been created as an extension method will create errors at compile-time, which you can quickly correct (even earlier, if you use Visual Studio). If you discover a mistake in the way you formulated a route, you only have to fix it in one place.
Although, instead of cluttering your UrlHelpers with extension methods, it might be better to have a static class called something like CommonUrls that holds static readonly properties (or static methods, if you prefer).
EDIT: I just realized that you would need to pass an instance of your UrlHelper to the CommonUrls class. Silly me. In that case, extension methods probably are the right tool for the job.
That's one person's opinion of what a best practice is. There are a few cases where it might be nice. If you have people working with the views while the URL structure is still being worked out you won't have to update the views once the URLs are finalized.
Should anyone else happen to stumble on this old post, I would suggest using the T4MVC templates by David Ebbo: See his latest blog post here.
I don't see this as a best practice. For one thing you're going down the path of burying structural specifics down in a bunch of extension methods. (Although you could use resources for the paths, it would mean high-friction changes.)
Further, at what point do you stop? For a site of any complexity you're going to need a lot of these helpers.
I've used a somewhat similar approach when referencing stylesheets, javascript, favicons, etc. although I use HtmlHelper rather the UrlHelper extensions as conceptually I think they're more suited to the task.
Further, because such things are typically added to a master page only, there's no issue with simply passing the complete path into the helper and having it construct an entire tag - rather than just resolve a URI.
I'm using this approch.
It's very useful when your application sitemap is subject to changes.
And yes, you need a lot of those (I my extension class count 1800 lines, with comments)
Main difference, in my case, I build the URL using a strongly-typed builder. It looks like this :
/// <summary>
/// To campaign 'transfer credits' page
/// </summary>
public static string ToCampaignTransferCredits(this UrlHelper helper, int? idCampaignSource)
{
return To<CampaignController>(helper, c => c.Transfer(idCampaignSource));
}
I think this is a very good practice (IMHO) for some reasons :
you have a clear separation between navigation available page/actions and your controllers. I recently had to move methods from one controller to another, and it worked without pain/refactoring/testing.
it's compiled so if you change a controller's method signature you are awared of the changes to do (and you only have 1 or 2 changes, no need to check the whole application)
you can use inheritance and generics on your controllers like a OOP geek, cascade the calls and whatever you find powerful, this approach will hide all the underlying complexity, leaving simples call in the views.

Resources