multiple Html.Attr on one tag in razor? - asp.net-mvc

how do i use multiple Html.Attr on one tag as follows in a razor view? this doesnt work.
<tr #Html.Attr("style", "color: #FF3D0D;")
#Html.Atrr("data-item", Model.ItemNumber)>

I'm not familiar with the .Attr helper either, but just incase you copied the code directly from your view, there is a typo, you have #Html.Atrr which I'm guessing should be #Html.Attr for data-item

So, it has come to this..
#Html.Atrr("data-item", Model.ItemNumber)
- VS -
data-item="#Model.ItemNumber"
Just one word: don't. Your markup AND every single human being on earth will benefit from the later much straight forward syntax. The HtmlHelper Html.Atrr doesn't help at all, no value.
Also, the following works for me:
<body #Html.Raw("data-test1=\"1\"") #Html.Raw("date-test2=\"2\"")>
.. and renders:
<body data-test1="1" date-test2="2">

You probably should be using #Html.Attr and not #Html.Atrr... or, as others have pointed out, just writing the attributes explicitly.

Related

String.format help needed with mvc 3 razor (vb.net) please?

I've inherited some code... and am trying to convert it to use MVC 3, with Razor, the VBHTML is as follows:
For Each Message As MessageDetailsModel In Model.Messages
#<div id='#Message.HeaderId' class='#Message.HeaderCss' onclick=#(String.Format("shMsgTree('{0}','{1}',{2},'{3}');", Message.HeaderCss, Message.HeaderId, Message.MessageId, Message.UserId))>
... more stuff...
</div>
Next
Stepping through the code, the String.format resolves to this:
shMsgTree('sh_msg_GridItem sh_msg_MessageRead ','divHeader0',40,'{85A433F0-4054-42E7-B778-3EF005E411D3}');
which is what I want on the page, but for some reason, it gets output on the page as this:
shMsgTree('sh_msg_GridAltItem" sh_msg_MessageRead="
The properties on the model are all strings.
Am at a bit of a loss as to how to get it to render. Originally the entire onclick javascript was being returned in the Model, but that didn't render any better either.
Any suggestions would really be welcome. Thanks!
Given our conversation in the comments and the fact that the original Razor is quite hard to read, I think I'd recommend either:
writing a Razor Helper for this small block of code http://weblogs.asp.net/scottgu/archive/2011/05/12/asp-net-mvc-3-and-the-helper-syntax-within-razor.aspx
or writing a normal Extension Method to output the code - http://weblogs.asp.net/jgalloway/archive/2011/03/23/comparing-mvc-3-helpers-using-extension-methods-and-declarative-razor-helper.aspx (this is what I would choose!)
Without stepping through it in code, it's too hard to read the syntax as currently written - so break it out into a separate compact, testable, readable component.
Hope that helps
Stuart
Not sure if this will do it, but your onClickcode needs to be wrapped in quotes, before and after: onClick="#(String.Format(...))"

Custom HTML Helpers in Razor & HTML Extension Methods

There are a lot of questions, here and everywhere, regarding the impossibility of using HtmlHelper extension methods (like ActionLink) in an #helper (razor) method.
Right now, in my project, I solved the problem passing as an extra parameter the current page (System.Web.Mvc.WebViewPage page) to the #helper, like in
#helper HelperFunction(SampleParameter sp, System.Web.Mvc.WebViewPage page)
and using it (trivially) as in
{
...
#page.Html.ActionLink("Title", "Action")
...
}
I would like to know if it's too stupid :-), and why. It would be better, of course, to have direct access to the current HtmlHelper of the page where the #helper is called, but, anyway... if this a good solution...
Andrea
I was curious why this didn't work, so I had a little look.
When you put code into the App_Code folder, it inherits from System.Web.WebPages.HelperPage and although this has a Html property, it's a System.Web.WebPages.HtmlHelper and not a System.Web.Mc.HtmlHelper, which is why you can't find things like ActionLink on it :(
I had a quick look around, and found this answer from Andrew Nurse:
Omar's got the right answer here, but
I wanted to add something (do feel
free to mark Omar's response as the
answer).
We were aware of this in v1 and
weren't able to get a great fix in the
product, but David Ebbo (an architect
on the ASP.Net team) posted a sample
of a Visual Studio Code Generator that
is basically a first exploration of
the kind of ideas we're looking at to
make this work properly:
http://blogs.msdn.com/b/davidebb/archive/2010/10/27/turn-your-razor-helpers-into-reusable-libraries.aspx
Try that out and see what you think!
Let David know if you have comments by
posting on his blog.
Unfortunately, it looks like you can't even put the Helper outside of App_Code into your Layout class or _ViewStart :(

Is it a good idea to create a helper method for this type of scenario?

I have this code in my html.erb at many places.
<div id="left-nav">
<%= render :partial => 'tests/tests_left_menu' %>
</div>
Is it a good idea to create helper method for this type of code ?
How to write this code in helper ?
I see a few good strategies to use in your situation. Pick and choose based on your project's specific requirements.
You can just put div#left-nav and its contents into yet another partial like tests/tests_left_menu_with_wrapper. This saves you a couple of lines.
If you can generalize the cases when the entire segment appears, you can move it into a layout. This way, once you declare the layout for a particular action using the ActionController::Base.layout method, you'll be able to skip writing the entire segment altogether.
You can write a helper, but it's not clear what advantage it confers over simply using content_tag. You're probably better off using partials or layouts.
Personally i don't think there's a need to, and i think it's more like because you are not using other tools like haml to help reduce the number of lines in an erb files
the same code can be achieved in haml in just 1 line:
#left-nav= render :partial => 'tests/tests_left_menu'
hope this helps =)
I suppose if you have that code in many places I'd move the the div into the partial. If you need the flexibility to have tests_left_menu outside of the div I'd still pick two partials over a helper in this scenario. Avoid writing html in Ruby when you can :)

Should I make a ImageHelper in this situation?

Hi I'm working with a project (asp.net mvc) where I need to show pictures on one site. They gone have jquery and be surrounded by a div like <div><img/></div>
I'm relatively new on MVC so I'm not sure what ways are the best to work in it yet. Should I do a ImageHelper so i can access it like <% Html.ImageJquery() %> or should i just do it plain in the view
what are your thoughts on this?
I am not sure if there is any single best practice for this case. As you already said you could create an extension method on a HtmlHelper or just put the code in the view.
Because the "added" code is a very simple (just two divs) I would skip extension method and just add the divs in the view. But if the code is actually more complex I would create a helper.
Cheers!
It depends how often you would use the helper. If it is used in a couple of places it would make sense, because it helps you to reduce redundant code.
The other option you have are partials.
I would go with an Extension method on the HTMLHelper , so that it accepts the 'src' value as a parameter and constructs the image tag accordingly.
Regarding Rendering of UI elements , i did read a blog post on 'Conditional Rendering' which i thought you would find it interesting .
please check the link below .
Conditional Rendering
Thanks ,
Vijay.

Why shouldn't Helpers have html in them?

I have heard that it's best not to actually have any html in your helpers; my question is, Why not? And furthermore, if you were trying to generate an html list or something like that, how can I avoid actual tags?
Thanks!
-fREW
My advice - if it's small pieces of HTML (a couple of tags) don't worry about it. More than that - think about partials (as pulling strings of html together in a helper is a pain that's what the views are good at).
I regularly include HTML in my helpers (either directly or through calls to Rails methods like link_to). My world has not come crashing down around me. In fact I'd to so far as to say my code is very clean, maintainable and understandable because of it.
Only last night I wrote a link_to_user helper to spits out html with normal link to the user along with the user's icon next to it. I could have done it in a partial, but I think link_to_user is a much cleaner way to handle it.
I don't see that there's anything wrong with it. The majority of the rails helpers generate HTML code (which is their purpose) - to me this implies that's what you're supposed to do yourself.
There is however the ever-present issue of code readability. If you have a helper which just builds a big string of raw HTML, then it's going to be hard to understand. While it's fine to generate HTML in helpers, you should do it using things like content_tag, and render :partial rather than just return %Q(<a href="#{something}">#{text}>)
This isn't a full answer to your question, but you can create html in your tags via the content_tag method. My guess as to why would be cleanliness of code.
Also, content_tag allows you to nest tags in blocks. Check out this blog post on content_tag.
On Rails 3 you can use *html_safe* String method to make your helper methods return html tags that won't be escaped.
As mentioned before, helpers are generally thought to be used as business logic, for doing something that drives view code, but is not view code itself. The most conventional place to put things that generate snippets of view code is a partial. Partials can call a helper if needed, but for the sake of keeping things separated, it's best to keep business in the helper and view in the partial.
Also, bear in mind this is all convention, not hard and fast rules. If there's a good reason to break the convention, do what works best.
I put html into partials usually.
Think about semantics. If you put html in a string, you lose the semantic aspect of it: it becomes a string instead of markup. Very different. For example, you cannot validate a string, but you can validate markup.
The reason I wanna put html in a helper instead of partial (and how I found this thread) is terseness. I would like to be able to write =hr instead of =render 'hr'.
To answer the question I didn't ask ;-) : to un-escape HTML in a helper, try this
def hr
raw '<hr />'
end

Resources