Hixx
Hixx

Reputation: 31

Call Method in Controller from View(cshtml)

Hi im trying to call a method from controller from view just to display the "staff_name"

Controller

 public JsonResult getStaffName(int staff_id)
    {
        var staffname = (from a in db.master_staff where b.staff_id == staff_id 
            select a.staff_name).SingleOrDefault();

        return Json(staffname,JsonRequestBehavior.AllowGet);
    }

View

int[] staff_id = { 24,25,26 }; 

@foreach (var n in staff_id){ 

//call method getStaffName from Controller to get "staff_name" 

}

it suppose to get the "staff_name" according to the "staff_id"

is there any possible method for this situation?

Upvotes: 0

Views: 11534

Answers (3)

Aleksej Vasinov
Aleksej Vasinov

Reputation: 2797

Do not do this. It is the way to the Dark side :) And each JSON request is taking some time.

  1. Create model to store your staff
  2. Fill it in controller (or even better in some business logic class)
  3. Display in your view

    public ActionResult Staff()
    {
        // This would be nice to have as separate Data Access Layery class
        var staffs = GetStaffs();
        return View(staffs);
    }
    
    private static StaffDto[] GetStaffs()
    {
        // One call to database is better that several
        var staffs = db.master_staff
            .Where(x => x.staff_id > 0) // Any other condition, if needed
            .Select(x => new StaffDto(x.staff_id, x.staff_name))
            .ToArray();
        return staffs;
    }
    
    // Data Transfer Object class to separate database from presentation view
    public class StaffDto
    {
        public int StaffId { get; set; }
        public string Name { get; set; }
        public StaffDto(int staffId, string name)
        {
            StaffId = staffId;
            Name = name;
        }
    }
    

Your view file (Staff.cshtml in my case)

@model IEnumerable<TestMvc.Controllers.StaffDto>
<div>
@foreach (var staff in Model)
{
    @staff.Name<br />
}
</div>

And, as bonus, you could unit test it easily

private readonly HomeController _homeController = new HomeController();

[TestMethod]
public void Staff_CheckCount()
{
    var result = _homeController.Staff();

    Assert.IsInstanceOfType(result, typeof(ViewResult));
    var actual = ((ViewResult)result).Model as StaffDto[];
    Assert.IsNotNull(actual);
    Assert.AreEqual(3, actual.Length);
}

Upvotes: 1

pinkar kumari
pinkar kumari

Reputation: 11

To call method from controller to view you have to use ajax call from view. here is ajax call syntax in asp.net mvc:

 $.ajax({ 
          type: "GET", 
          url: '@Url.Action("controller method name", "controller name")', 
          data: { searchText: value }, 
          contentType: "application/json; charset=utf-8", 
          dataType: 'json', 
          success: function (result) { 
           },
           error: { 
           } 
        }); 
  1. type can be GET or POST depending on your controller method type.
  2. In URL attribute two parameters are passed the first one is controller method name and second one is controller name.
  3. In data attribute you have to pass the values which are required to pass in controller from view such as parameters in controller method.
  4. In success and error attribute you have to write a block of code which should be executed in both cases. such as display data on UI upon success and error message on failure.

Upvotes: 1

Marcel Kirsche
Marcel Kirsche

Reputation: 455

You can do it like this:

@Html.Action("getStaffName", "YourController", staff_id)

For more info, look at child actions: https://haacked.com/archive/2009/11/18/aspnetmvc2-render-action.aspx/

However, I do not know what you are trying to achieve with this.

Upvotes: 1

Related Questions