Reputation: 9044
I have ASP.Net MVC 5 application I want to call a method from view how can I do it?
my code:
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 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());
}
Upvotes: 1
Views: 7224
Reputation:
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>
}
Upvotes: 4
Reputation: 1554
You can achieve this purpose in many ways, on of them is you call make a ajax call to controller method. Something like this
$('#btnSave').click(function () {
$.ajax({
url: "/ContollerName/GetRoleNameById" + "?RoleId=1", // change controller name here and pass proper role id.
type: "GET",
success: function (data) {
if (data.status == "Success") {
alert("Done");
} else {
alert("Error occurs on the Database level!");
}
},
error: function () {
alert("An error has occured!!!");
}
});
});
Also you can set content type in calling configuration
Upvotes: 0