Reputation: 1403
I'd like to have a list that will shorten a field value if it is too long from a linked Entity Data Model. Something where I could take the following:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<MvcDR.Models.DONOR_LIST>>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<h2>Lists</h2>
<table>
<tr>
<th></th>
<th>LIST_NAME</th>
<th>SUMMARY</th>
</tr>
<% foreach (var item in Model) { %>
<tr>
<td><%: Html.ActionLink("Details", "Society", new { id = item.DONOR_LIST_ID })%> |</td>
<td><%: item.LIST_NAME %></td>
<td><%: item.SUMMARY%></td>
</tr>
<% } %>
</table>
and replace
<td><%: item.SUMMARY%></td>
with
<td><%: item.SHORT_SUMMARY%></td>
doing so in Ruby is pretty straight forward, but I am unsure of how to do so working within the Entity data model of asp.net mvc.
Upvotes: 1
Views: 3711
Reputation: 1335
I would make a Extension method for string that shortens text... Then you can reuse it on any field...
namespace Helpers
{
public static class StringExtensions
{
public static string ShortenMyString(this string s, int length)
{
// add logic to shorten the string....
}
}
Upvotes: 1
Reputation: 23157
You could also do this with an extension method. I'm typing this from scratch, without benefit of an IDE, so please excuse any typos:
public static class Extensions
{
public static string Shorten(this string str, int maxLen)
{
if(str.Length > maxLen)
{
return string.Format("{0}...", str.Substring(0, maxlen));
}
return str;
}
}
Then in your asp.net code:
<td><%: item.SUMMARY.Shorten(100) %></td>
Upvotes: 1
Reputation: 5749
I've usually solved this in the past by creating a ViewModel class that represents a view-specific version of some EF model class. You can use something like AutoMapper to help do the "grunt work" of one-to-one field mapping, but then add a calculated SHORT_SUMMARY
field of your own.
You then change your view to use the view model:
Inherits="System.Web.Mvc.ViewPage<IEnumerable<MvcDR.Models.DONOR_LIST_VIEW>>"
Upvotes: 1
Reputation: 14350
Will something like this work?
namespace MvcDR.Models
{
public partial class DONOR_LIST
{
public string SHORT_SUMMARY
{
get
{
int desiredMaxStringLength = 100;
return SUMMARY.Substring(0, desiredMaxStringLength) + "...";
}
}
}
}
Upvotes: 0