Simple way to make comma separated list of DisplayFor - asp.net-core

There is pattern I used a lot of in ASP.NET MVC 5:
(string.Join("<br>", someList.Select(item => Html.DisplayFor(model => item)))
But in ASP.NET Core DisplayFor(..) now returns IHtmlContent, and IHtmlContent.ToString() now returns literaly "Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.ViewBuffer", not a rendered content.
Which pattern should I use to fix code with minimal changes?
Which pattern is an idiomatic way to achieve this?

Related

Simple paragraph formatting of strings in mvc 4 or 5

I'm using MVC 4 I have a string being stored in SQL Server as varchar(Max) my data annotations in the model specify DataType(DataType.MultilineText). I would think that the helpers for displaying this type of text would not just spit it all out on one line, but none of the formatting from the multiline text box is coming through when I display it on a page using the basic scaffolding. But the formatting does show up when I go to edit that description on the crud side. Why is this so hard to do out of the box. I can use a MVC 4 or 5 solution. I would think they would be similar.
I use the following methods to display on my page:
#Html.DisplayNameFor(model => model.InstructionEn)
&
#recipe.RecipeInstructionsEn
I'm thinking something that will replace New lines with tags might work. But how would I go about that? I know the New line formatting is there.
I also thought about using markdown, but wouldn't know where to start.
You need to replace the plain text newline character (\n) with the HTML one (<br />):
#Html.Raw(recipe.RecipeInstructionsEn.Replace("\n", "<br />"))
The use of Html.Raw prevents the default HTML encoding that Razor applies. Without it, the newline entity will display as "<br />" instead of acting as an HTML line break.

laravel 4 pattern filter using a wildcard

I started using Laravel 3 last week, and then found the new 4 release and I'm trying to convert now.
I have a dozen+ routes that I want to deliver to a specific controller method. i.e., "/api/v1/owners/3/dogs/1 or /api/v1/owners/3" to run "myresourcecontroller#processRequest"
In Laravel 3 I was able to use this: (note * wildcard)
Route::any('api/v1/owners*', 'owners#processRequest'); // Process tags resource endpoints
I found this example from the documentation but it gives me an error. I get a NotFoundHttpException.
//[Pattern Based Filters](http://laravel.com/docs/routing#route-filters)
Route::filter('admin', function()
{
//
});
Route::when('admin/*', 'admin');
Not sure what I'm doing wrong? Is there another way to do this?
I don't want to use the Laravel 4 restful controllers, cause they don't seem to conform to complete restful design. i.e., no verbs in the url.
I have all of my processing written, I just need to be able to route to it.
I need to be able to create new records by POST /api/v1/owners or /api/v1/owners/3/dogs
I cannot use /api/v1/owners/create.
I'm trying to avoid having to write a route for every endpoint, i.e.,
Route::any('api/v1/owners/{owner_id}', 'owners#processRequest');
Route::any('api/v1/owners/{owner_id}/dogs/{dog_id}', 'owners#processRequest');
Thank you for any help
You should make use of resourceful controllers as they're a great asset when building an API. The endpoints you described can be achieved using resource controllers and nested resource controllers.
Route::resource('owners', 'OwnersController');
Route::resource('owners.dogs', 'OwnersDogsController');
Would allow you to create an owner with POST localhost/owners and create a dog on an owner with POST localhost/owners/3/dogs.
You can then wrap these routes in a route group to get the api/v1 prefix.
Route::group(['prefix' => 'api/v1'], function()
{
Route::resource('owners', 'OwnersController');
Route::resource('owners.dogs', 'OwnersDogsController');
});
Haven't used Laravel myself, but try any('api/v1/owners/*', (note slash before asterisk) as in the example.

ASP.net MVC: Execute Razor from DB String?

I was thinking about giving end users the ability to drop Partial Views (controls) into the information being stored in the database. Is there a way to execute a string I get from the database as part of the Razor view?
Update (I forgot all about this)
I had asked this question previously (which lead me to create RazorEngine) Pulling a View from a database rather than a file
I know of at least two: RazorEngine, MvcMailer
I have a bias towards RazorEngine as it's one that I've worked on but I have a much simpler one at Github called RazorSharp (though it only supports c#)
These are all pretty easy to use.
RazorEngine:
string result = RazorEngine.Razor.Parse(razorTemplate, new { Name = "World" });
MvcMailer
I haven't used this one so I can't help.
RazorSharp
RazorSharp also supports master pages.
string result = RazorSharp.Razor.Parse(new { Name = "World" },
razorTemplate,
masterTemplate); //master template not required
Neither RazorSharp, nor RazorEngine support any of the Mvc helpers such as Html and Url. Since these libraries are supposed to exist outside of Mvc and thus require more work to get them to work with those helpers. I can't say anything about MvcMailer but I suspect the situation is the same.
Hope these help.

Rails I18n: shorten the translate calls (at least in the views)

What is the DRY way to translate certain fields?
In my RESTful views, I have some repeating snippets, like this in a show-view:
...
<dt><%= t("activerecord.attributes.user.firstname") %></dt>
<dd><%= #user.firstname %></dd>
...
Now, instead of writing t("activerecord.attributes.user.attr_name") over and over again, I'd like to write only t(:attr_name) (similar to f.label :firstname in the form-views).
Basically, this should not be a problem (at least for the RESTful views), since the I18n module could query the controller method to extrapolate the model name and then just guess the correct translation string.
My question: Did anyone have practical experience with this approach? Could there even be a RubyGem for it? Or: are there pitfalls, I didn't think of?
I seems, ActiveModel::Translation#human_attribute_name does the trick (e.g. <%= User.human_attribute_name :firstname %>).
The recommended way to do this is to put this into a partial (e.g. app/views/user/_form.html.erb or even app/views/user/_user.html.erb), and then precede the name with a leading dot, thus:
<dt><%= t(".firstname") %></dt>
<dd><%= user.firstname %></dd>
More information: examples (from Agile Web Development with Rails); Rails documentation

Can you remove the _snowman in Rails 3?

I'm building an app on Rails 3 RC. I understand the point behind the _snowman param (http://railssnowman.info/)...however, I have a search form which makes a GET request to the index. Therefore, submitting the form is creating the following query string:
?_snowman=☃&search=Box
I don't know that supporting UTF encoding is as important as a clean query string for this particular form. (Perhaps I'm just too much of a perfectionist...hehe) Is there some way to remove the _snowman param for just this form? I'd rather not convert the form to a POST request to hide the snowman, but I'd also prefer it not be in my query string. Any thoughts?
You can avoid the snowman (now a checkmark) in Rails 3 by.... not using Rails for the search form. Instead of using form_tag, write your own as outlined in:
Rails 3 UTF-8 query string showing up in URL?
Rails helpers are great unless they're not helping. Do-it-yourself is good as long as you understand the consequences, and are willing to maintain it in the future.
I believe the snowman has to be sent over the wire to ensure your data is being encoded properly, which means you can't really remove the snowman input from forms. Since, it's being sent in your GET request, it will have to be appended to the URL.
I suppose you could write some javascript to clean up the URL once the search page loads, or you could setup a redirect to the equivalent URL minus the snowman. Both options don't really feel right to me.
Also, it doesn't seem there is any way to configure Rails to not output it. If you really wanted to get rid of it, you could comment out those lines in Rails' source (the committed patches at the bottom of railssnowman.info should lead you to the files and line numbers). This adds some maintenance chores for you when you upgrade Rails. Perhaps you can submit a patch to be able to turn this off?
EDIT: Looks like they just switched it to what looks like a checkmark instead of a snowman.
EDIT: Oops, back to a snowman.
In Rails 4.1 you can use the option :enforce_utf8 => false to disable utf8 input tag.
However I want to use this in Rails 3, so I monkey-patched my Rails. I put the following in the config/initializers directory.
# allow removing utf8 using enforce_utf8, remove after Rails 4.1
module ActionView
module Helpers
module FormTagHelper
def extra_tags_for_form(html_options)
authenticity_token = html_options.delete("authenticity_token")
method = html_options.delete("method").to_s
method_tag = case method
when /^get$/i # must be case-insensitive, but can't use downcase as might be nil
html_options["method"] = "get"
''
when /^post$/i, "", nil
html_options["method"] = "post"
token_tag(authenticity_token)
else
html_options["method"] = "post"
tag(:input, :type => "hidden", :name => "_method", :value => method) + token_tag(authenticity_token)
end
enforce_utf8 = html_options.delete("enforce_utf8") { true }
tags = (enforce_utf8 ? utf8_enforcer_tag : ''.html_safe) << method_tag
content_tag(:div, tags, :style => 'margin:0;padding:0;display:inline')
end
end
end
end