2010-08-13 74 views
1

我想要一个列表,如果字段值距链接的实体数据模型太长,它将缩短字段值。东西在那里我可以采取如下:向asp.net mvc模型添加一个计算的字段

<%@ 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> 

并更换

 <td><%: item.SUMMARY%></td> 

 <td><%: item.SHORT_SUMMARY%></td> 

在Ruby中这样做是非常简单的,但我不确定如何做到这一点在asp.net mvc的实体数据模型中工作。

+0

你的意思是显示一个较短的版本(或切断与一些点文字......)如果概要的概要的即大于15 0个字符? – 2010-08-13 17:13:50

+0

http://stackoverflow.com/questions/271398/what-are-your-favorite-extension-methods-for-c-codeplex-com-extensionoverflow/1512463#1512463 – Omar 2010-08-13 18:14:34

回答

0

您还可以用扩展方法做到这一点。我从头开始打字,没有一个IDE的利益,所以请原谅任何错字:

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; 
    } 
} 

然后在您的asp.net代码:

<td><%: item.SUMMARY.Shorten(100) %></td> 
+0

哦,我非常喜欢这个。一个问题,最佳实践是什么,或者在项目的哪个位置放置这种扩展方法已被接受。 – Lloyd 2010-08-13 17:48:51

+0

我回过头来看这个答案,@server_info有很好的名字空间。为了跟进我的问题,我创建了一个名为“Helper”的文件夹。我也检查了空值并返回null以允许。 然后在视图页面上在页面声明部分添加了<%@ Import Namespace =“Helpers”%>。 – Lloyd 2010-08-13 18:20:26

+0

就是这样做的。 :) – Robaticus 2010-08-13 18:25:39

0

会这样的工作?

namespace MvcDR.Models 
{ 
    public partial class DONOR_LIST 
    { 
     public string SHORT_SUMMARY 
     { 
     get 
     { 
      int desiredMaxStringLength = 100; 
      return SUMMARY.Substring(0, desiredMaxStringLength) + "..."; 
     } 
     } 
    } 
} 
1

我已经在过去通过创建ViewModel类,表示一些EF模型类的视图特定的版本通常解决了这个。您可以使用像AutoMapper这样的内容来帮助完成一对一字段映射的“咕噜工作”,但随后添加一个您自己的计算的SHORT_SUMMARY字段。

然后,您更改您的视图使用视图模型:

Inherits="System.Web.Mvc.ViewPage<IEnumerable<MvcDR.Models.DONOR_LIST_VIEW>>" 
+0

我是ViewModel方法的忠实粉丝, MVC。我们有一个应用程序,我们开始使用传统的MVC方法,然后采用ViewModels。事情变得更简单的ViewModels维护。 – Robaticus 2010-08-13 17:29:30

+0

我的确如此。我想我会开始在我的项目中添加更多的ViewModels。 – Lloyd 2010-08-13 18:22:58

1

我会做的字符串扩展方法该缩短的文字... 然后你可以重复使用它在任何领域...

namespace Helpers 
{ 
    public static class StringExtensions 
    { 
     public static string ShortenMyString(this string s, int length) 
     { 

      // add logic to shorten the string.... 
     } 
    } 
+0

看起来有点像我的:) – Robaticus 2010-08-13 17:43:07