Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC - calling controller from view

I am new to MVC

I am developing a web application using MVC and the application contains only one page.

So in that view I have to populate multiple data. Say if the application is a "News feed" application, i need to populate recent news, news liked by you, news recommended by your friends etc. So should I make a ajax call from view to all required controllers to fetch these data and append in the view??

Currently i am able to get the data by making an ajax call to controller and fetching the data, but as per my understanding, the controller is called first in a MVC and it renders the view and in the way i am currently using I am calling the controller back from view.

Is this method correct ?? what is the right approach to achieve this result in MVC?

If i have to use Ajax call to controller and get data, what is going to be the different in MVC? In 3-tier app i will make ajax call to some web method or a Handler which will return some data here I am calling an action result function which is again returning some data

like image 372
Vignesh Subramanian Avatar asked Jan 16 '14 07:01

Vignesh Subramanian


People also ask

How do you call a controller method from a razor page?

We can use @html. action to call controller method.


2 Answers

Yes you can use ajax call like this

$(document).ready(function () {
            $('#CategoryId').change(function () {
                $.getJSON('/Publication/AjaxAction/' + this.value, {},
                  function (html) {
                      $("#partial").html(html);

                      alert("go");
                  });
            });
        });

and then load a partial view from your contoller.

public ActionResult AjaxAction(int Id)
        {
            if (Request.IsAjaxRequest())
            {
                if (Id== 1)
                {
                    ViewBag.SourceTypeId = new SelectList(db.SourceTypes, "Id", "Title");
                    ViewBag.CityId = new SelectList(db.Cities, "Id", "Title");
                    return PartialView("_CreateStatya");
                }
            }
            return PartialView();
        }
like image 57
Sajeev Avatar answered Sep 20 '22 13:09

Sajeev


you can use ChildActionOnly :

[ChildActionOnly]
public ActionResult GetLatestNews()
{
  //...
  return PartialView("yourView",yourquery);
}

and call that in your view this way :

 @Html.Action("GetLatestNews","Home")
like image 36
Sirwan Afifi Avatar answered Sep 20 '22 13:09

Sirwan Afifi