Reputation: 1207
So basically I want to know how to call methods or right a code in the razor files
I've seen some ways over the internet that includes static classes, but I think it's not the best way to do that.
I got this code in the cshtml file:
<td>
@Html.DisplayFor(modelItem => item.Description)
</td>
that displays all the rows from "News" class ( in the Model )
And I want to display only the first 50 letters of the description and 3 dots afterwards, my question is where should I write this method? in the "News" class? or in another external class? and how can I access it in the razor file?
Upvotes: 3
Views: 80
Reputation: 129
Updated To reflect @mjwills suggestions
You could define(write) the method as a member method of your News Model class
public class NewsModel
{
//all your properties here
public string Description { get; set; }
public string DescriptionWithDots { get { return DoTheDots(Description); } }
//the method that writes the dots
public string DoTheDots(string input)
{
return input + "some dots ...";
}
}
Then in the view to call it just don't use the Displayfor() and call it like this:
<td>
@item(item.DescriptionWithDots)
</td>
As @ath said above this is not great practice (as you are now coupling the view to the model and skipping the controller), you want to avoid calling methods in the view.
Instead you could refactor it into your Controller:
foreach (var item in models)
{
item.Description = item.DoTheDots(item.Description);
}
return View(models);
Upvotes: 1