简体   繁体   中英

Trouble calling C# method in partial class from view using MVC 6

I have a database table called Skill used to generate my model with a field SkillIndex that is a smallint (byte) indexing into an enumerated type SkillEnum. I want to map the enumerated type values to their String counterparts with skillToString() . When I call the index link created by the view, the item generated is not parsed. Here are the details:

PARTIAL CLASS (part of):

namespace RpgApp2.Models
{
  public enum SkillEnum { Appraise, Bluff, Climb, Diplomacy, Intimidate, Jump, Perception };

  [MetadataType(typeof(SkillMetaData))]
  public partial class Skill
  {
    Utility util;

    public String skillToString()
    {
        byte i = (byte) this.SkillIndex;
        switch (i)
        {
            case (byte)SkillEnum.Appraise: return "Appraise";
            case (byte)SkillEnum.Bluff: return "Bluff";
            case (byte)SkillEnum.Diplomacy: return "Diplomacy";
            case (byte)SkillEnum.Climb: return "Climb";
            case (byte)SkillEnum.Intimidate: return "Intimidate";
            case (byte)SkillEnum.Jump: return "Jump";
            case (byte)SkillEnum.Perception: return "Perception";
            case (byte)SkillEnum.Ride: return "Ride";
            case (byte)SkillEnum.Spellcraft: return "Spellcraft";
            case (byte)SkillEnum.Survival: return "Survival";

            default: return "No matching skill for " + (int)i;
        }

VIEW source code (Index.cshtml, partial):

@foreach (var item in Model) {
  <tr>
    <td>
        @Html.DisplayFor(modelItem => item.CharacterIndex)
    </td>
    <td>
         <% item.SkillToString(); %>
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Ranks)
    </td>

OUTPUT SOURCE (ie view source of page generated in Internet Explorer:

<tr>
    <td>
        1
    </td>
    <td>
         <% item.SkillToString(); %>
    </td>
    <td>
        1
    </td>
    <td>
        3
    </td>

The <% item.SkillToString(); %> <% item.SkillToString(); %> renders as itself and appears blank in the web page, whereas I want "Diplomacy" to appear for the value of 3.

What do I need to get the method skillToString() method called on the current item (ie, a Skill)?

由于您使用的是Razor视图引擎,因此可以使用:

@item.SkillToString()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM