MVC-从视图调用控制器 [英] MVC - calling controller from view
问题描述
我是MVC的新手
我正在使用MVC开发Web应用程序,该应用程序仅包含一页.
I am developing a web application using MVC and the application contains only one page.
因此在该视图中,我必须填充多个数据.假设该应用程序是新闻提要"应用程序,则需要填充最近的新闻,您喜欢的新闻,您的朋友推荐的新闻等.因此,我应该从视图向所有必需的控制器进行ajax调用以获取这些数据并追加在视图中?
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??
当前,我能够通过对控制器进行ajax调用并获取数据来获取数据,但是据我的理解,该控制器首先在MVC中被调用,它以我当前使用的方式呈现视图我正在从视图中回叫控制器.
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.
此方法正确吗?在MVC中达到此结果的正确方法是什么?
Is this method correct ?? what is the right approach to achieve this result in MVC?
如果我必须使用Ajax调用控制器并获取数据,那么MVC中会有什么不同? 在3层应用程序中,我将对某些Web方法或处理程序进行Ajax调用,该处理程序将返回一些数据 在这里,我正在调用一个动作结果函数,该函数再次返回一些数据
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
推荐答案
是的,您可以像这样使用ajax调用
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();
}
这篇关于MVC-从视图调用控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!