开发者

Add a calculated field to asp.net mvc model

开发者 https://www.devze.com 2023-01-11 05:59 出处:网络
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:

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>
    &l开发者_运维技巧t;% 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.


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>


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>>"


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


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) + "...";
         }
      }
   }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号