MVC - controller call from view

I am new to MVC

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

So I have to fill in some data. Say, if the application is the News Feed application, I need to fill in the latest news, the news I like, news recommended by your friends, etc. So I have to make an ajax call from the view to all the required controllers to extract this data and add in the view

Currently I can get data by making an ajax call to the controller and retrieving the data, but as I understand it, the controller is called first in MVC and displays the view and the way I am currently using I call the controller back from the view.

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

If I need to use the Ajax call for the controller and get the data, what will be different in MVC? In a 3-tier application, I will make an ajax call for some web method or handler that will return some data here, I call the action result function, which returns some data again

+8
c # asp.net-mvc asp.net-mvc-3 asp.net-mvc-4
source share
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 the partial view from your controller.

 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(); } 
+6
source share

you can use ChildActionOnly :

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

and name it like this:

  @Html.Action("GetLatestNews","Home") 
+3
source share

All Articles