简体   繁体   中英

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

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());
    }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM