AsP.Net MVC 5如何在视图中调用函数
问题描述:
我有ASP.Net MVC 5应用程序,我想从视图中调用方法该怎么做?
I have ASP.Net MVC 5 application I want to call a method from view how can I do it?
我的代码:
我的UsersList函数:
My UsersList function:
public ActionResult UsersList()
{
var User_VM = new UserVM
{
MyUsers = context.Users.OrderBy(u => u.Email).Include(u => u.Roles).ToList()
};
return View(User_VM);
}
UsersList视图:
UsersList View:
@foreach(var user in Model.MyUsers)
{
<tr>
<td>@user.Email</td>
<td>
@foreach(var r in user.Roles)
{
<p>
@Html.Action(GetRoleNameById(r.RoleId))
</p>
}
</td>
</tr>
}
和我在控制器中的功能:
and my function in controller:
public ActionResult GetRoleNameById(string RoleId)
{
var RoleName = context.Roles.Where(r => r.Id == RoleId).FirstOrDefault();
return Content(RoleName.ToString());
}
答
您可以使用Html.Action()的rel ="nofollow noreferrer">重载,将动作名称作为第一个参数,并将路由值作为第二个参数
You can call your server method by using the overload of Html.Action()
that accepts the action name as the first parameter and the route values as the 2nd parameter
@foreach(var r in user.Roles)
{
<p>@Html.Action("GetRoleNameById", new { roleId = r.RoleId })</p>
}