从 javascript 函数调用控制器
我试图从 javascript 函数调用控制器方法,我读到它可以与 jquery .ajax 一起使用。问题是我不想接收结果,控制器根据我通过 ajax 发送的 id 呈现一个视图。我有以下代码,但它没有执行任何操作...
(此函数由 flash 对象调用)
function display(number) {
$.ajax({
type: "POST",
url: "/Controller/Method",
data: "id=" + number});
}
控制器的方法如下所示:
[HttpPost]
public ActionResult Method(int? id) {
object = //do the query.
return View(object);
}
I'm trying to call a controller method from a javascript function, I read that it can be used with jquery .ajax. The thing is that I don't want to receive a result, the controller renders a view based on the id that I send via the ajax. I have the following code, but it doesn't do anything...
(This function is called by a flash object)
function display(number) {
$.ajax({
type: "POST",
url: "/Controller/Method",
data: "id=" + number});
}
Here's what the controller's method looks like:
[HttpPost]
public ActionResult Method(int? id) {
object = //do the query.
return View(object);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果检测到 AJAX 请求,您可以返回
JsonResult
:You could return a
JsonResult
if you detect an AJAX request:如果您想通过ajax更新您的HTML,您应该在ajax请求的回调函数中更新您网站的内容。如果您只想导航到返回 HTML 的新页面,则可以使用 window.location 方法。
这两种情况,请确保您在 ajax 调用的成功回调函数上执行此操作。
If you want to update your HTML through ajax, you should update the contents of your website in the callback function of your ajax request. If you simply want to navigate to a new page with the HTML returned just then use the window.location method.
Both cases, ensure you do it on the success callback function of your ajax call.
您可以返回一个
PartialView
,它将返回可用于更新 DOM 的 HTML,但听起来您只想直接向 url 发出请求,在这种情况下,只需执行假设您有与您发出请求的 url 相匹配的路由,控制器操作可以从路由值中获取 id。
AJAX 请求通常适用于您想要与服务器通信而不执行全页请求和刷新的情况。通常,通信会返回一些内容,但并非总是如此,但如果它确实返回一些内容,那么通常会使用从服务器返回的数据以某种方式操作 DOM。
You can return a
PartialView
which will return HTML that you can use to update the DOM but it sounds like you just want to make a request to a url directly, in which case, simply doAssuming that you have a route that matches the url that you are making a request to, the controller action can take the id from the route values.
AJAX requests are generally for when you want to communicate with the server without performing a full page request and refresh. Usually that communication returns something, but not always, but if it does return something then it is common to manipulate the DOM in some way with the data returned from the server.