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
We can use @html. action to call controller method.
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();
}
you can use ChildActionOnly :
[ChildActionOnly]
public ActionResult GetLatestNews()
{
//...
return PartialView("yourView",yourquery);
}
and call that in your view this way :
@Html.Action("GetLatestNews","Home")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With