изменить данные отображения столбца метода индекса - PullRequest
1 голос
/ 04 августа 2020

У меня есть класс модели,

public class CustomerModel
    {       
        public int CustomerId { get; set; }
        
        public string CustomerName { get; set; }

        public int CustomerPoints { get; set; }
        
    }

В методе контроллера

public ActionResult Index()
        {
            return View(db.Customers.ToList());
        }
    

В столбце CustomerPoints я получаю целое число. Я хочу отобразить удобное сообщение для этого поля. Например,

If CustomerPoints value < 10 then bronze
CustomerPoints value >10 && < 20 silver
CustomerPoints value >20 && < 30 gold
CustomerPoints value >30 && < 40 diamond

Как я могу это сделать? Пожалуйста, помогите, я новичок в платформе MVC. Спасибо.

1 Ответ

0 голосов
/ 04 августа 2020

Сохраните класс модели, как показано ниже,

public class CustomerModel
{       
    public int CustomerId { get; set; }
    
    public string CustomerName { get; set; }

    public int CustomerPoints { get; set; }

    public List<CustomerModel> CustomerList { get; set; }
    
}

Сохраните метод действия, как показано ниже,

 public ActionResult Index()
    {
       
       CustomerModel model=new CustomerModel();
           
       model.CustomerList= (from n in db.Customers
                           select new CustomerModel 
                           {
                               CustomerPoints=n.CustomerPoints < 10 ? 
                                               "bronze":n.CustomerPoints >10 && 
                                                 n.CustomerPoints <20 ? "silver"
                           }).ToList();
        return View(model);
    }

И будет,

     @model CustomerModel  
   @{  
   
  }  
 <h2></h2>  

 
   <table class="table">  
 <tr>  
    
    <th>Customer Points </th>  
</tr>  

  @foreach (var item in Model.CustomerList ) {  
<tr>  
    <td>  
        @Html.DisplayFor(modelItem => item.CustomerPoints)  
    </td>  
    
</tr>  

}

...