1

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());
    }
12
  • Can you explain more? Commented Aug 12, 2017 at 6:29
  • 2
    Its a bit unclear why you would want to do this instead of populating the model in the main view in the first place, but its @Html.Action("GetRoleNameById", new { roleId = r.RoleId }) Commented Aug 12, 2017 at 6:30
  • 1
    @Html.Action("Controller","Name", new { id = 1 }) This is Default.. Change with your own Controller and Method Commented Aug 12, 2017 at 6:30
  • I need to call an method or action from View, do you know how to call? Commented Aug 12, 2017 at 6:30
  • 1
    Try above, it is perfect way to Call Commented Aug 12, 2017 at 6:31

2 Answers 2

4

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>
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.