AsP.Net MVC 5 how to call a function in view

心已入冬 提交于 2019-12-06 15:20:47

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>
}

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!