I have retrieved data from database using a LINQ query.
var data = (from z in db.BlogPostTbl
where z.PostId == id
select z).ToList();
in this result, I have an attribute name user_rankings
. The value for this field is [1,2,3]
in database but I have to display as good if 3, better if 2 or best if 1
. How can I do this?
<td><b>User Ranking:</b> @Html.DisplayFor(modelItem => item.user_rankings) </td>
CodePudding user response:
Example of using the Enum
type.
Defining the UserRankingEnum
type and the GetEnumDescription()
method to obtain a description by the enum
value:
using System.ComponentModel;
using System.Linq;
using System.Reflection;
namespace WebApp.Models
{
public class BlogPost
{
public int PostId { get; set; }
public int user_rankings { get; set; }
}
public enum UserRankingEnum
{
[Description("BEST")]
Best = 1,
[Description("BETTER")]
Better = 2,
[Description("GOOD")]
Good = 3
}
public static class EnumExtension
{
public static string GetEnumDescription(this UserRankingEnum value)
{
if (value.GetType().GetField(value.ToString()) is FieldInfo fi)
{
if (fi.GetCustomAttributes(typeof(DescriptionAttribute), false) is DescriptionAttribute[] attributes && attributes.Any())
{
return attributes.First().Description;
}
}
return value.ToString();
}
}
}
The view accordingly:
@using WebApp.Models
@model IList<WebApp.Models.BlogPost>
@foreach (var item in Model)
{
<div>
<b>User Ranking: </b>
@{ var description = ((UserRankingEnum)item.user_rankings).GetEnumDescription(); @Html.DisplayFor(m => description) }
</div>
}
CodePudding user response:
One possibility is to use a separate view model class / poco and map the db entity to this poco:
var data = (from z in db.BlogPostTbl
where z.PostId == id
select new BlogPostViewModel()
{
Ranking = GetRankingDescription(z.user_rankings)
}).ToList();
public class BlogPostViewModel
{
public string Ranking { get; set; }
}
private static string GetRankingDescription(int ranking)
{
switch (ranking)
{
case 1:
return "best";
case 2:
return"better";
case 3
return"good";
default
return "";
}
}
CodePudding user response:
I think you want something like this
// inside the razor page
@foreach (var item in Model)
{
string rank_ = "";
switch(item.user_rankings)
{
case "1":
ward_ = "BEST";
break;
case "2":
ward_ = "BETTER";
break;
case "3":
ward_ = "GOOD";
break;
}
<td><b>User Ranking:</b> @rank_ </td>
}
CodePudding user response:
I could have sworn that you can use the
public enum UserRankingEnum
{
[Description("BEST")]
Best = 1,
[Description("BETTER")]
Better = 2,
[Description("GOOD")]
Good = 3
}
and then
@Html.DisplayFor(modelItem => item.user_rankings)
Will display the description. In fact checked some code and it should do. Although it depends on what you need and things like multi-lingual reasons might mean you lean towards a table or some other way to support it.