El Hamza El Hamza - 18 days ago 5
C# Question

Call function into view razor

Hi Can I call a function into my view to get the description of ids in the foreach

My view

@if (Model != null)
{
int i = 1;
foreach (var item in Model)
{
<tr class="">
<td class="left">@{ new Fullname().getfullname(item.student_id.value).ToString(); }</td>
<td class="left"></td>
<td class="left">@CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(item.paid_month.Value).ToUpper()</td>
<td class="left">@item.monthly</td>
<td class="left">@item.transport</td>
<td class="left">@item.discount_details</td>
<td class="left">@item.total</td>
</tr>
}
}


in Fullname class

public class Fullname
{
private dbEntities db = new dbEntities();
public string getfullname(int? id)
{
var StudentSelect = db.student.Where(s => s.student_id == id)
.Select(s => new
{
FullName = s.lastname + " " + s.firstname
});


return StudentSelect.FirstOrDefault().FullName;
}
}


I'm trying to get the student fullname from the @item.student_id in the Model

but nothing displayed

thanks

Answer

The problem is that you retrieve the Fullname correctly, but you never emit it as string into the rendered view.

Use the @variableName syntax to emit the value of a C# variable as string:

@{ var fullname = new Fullname().getfullname(item.student_id.value).ToString(); }
<td>@fullname</td>