C# ASP.NET MVC 和 JQuery 向控制器获取信息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/414726/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 02:30:38  来源:igfitidea点击:

ASP.NET MVC and JQuery get info to controller

c#jqueryajaxasp.net-mvc

提问by Buddy Lindsey

I am totally confused on how to do ajax stuffs with jQuery and it seems the more I try the more confused I get. At this point all I want to do is get data to my controller using jQuery ajax. Some code for my jquery ajax call is.

我对如何用 jQuery 做 ajax 的东西完全感到困惑,似乎我尝试的越多,我就越困惑。在这一点上,我想要做的就是使用 jQuery ajax 将数据发送到我的控制器。我的 jquery ajax 调用的一些代码是。

$(function() {
    $('#buttonAddLink').click(function() {
        var AjaxLink = {
            title: $("#linkTitle").val(),
            url: $("#linkUrl").val()
        };

        $.ajax({
            url: '/User/AddLink',
            type: 'POST',
            data: AjaxLink,
            dataType: 'json',
            success: function(result){
                $('.added').html(result.Result).show();
            }
         });         
    });    
});

Here is my controller and Action I am using. From trying to look at several tutorials it "should" work to the best of my knowledge, but apparently I don't get it like I thought I did.

这是我正在使用的控制器和操作。据我所知,从尝试查看几个教程来看,它“应该”起作用,但显然我并没有像我想象的那样理解它。

public ActionResult AddLink(string title, string url)
{
    return Json(new { Result = string.Format(title + " " + url)});
}

All I am basically trying to do with that is do the Ajax call and return it to display just to make sure data was sent to the controller.

我基本上要做的就是执行 Ajax 调用并将其返回以显示,以确保将数据发送到控制器。

回答by foxxtrot

It has to do with the way you're structuring your request. Your JQuery call is sending the data to the AddLink action on the User controller as POST data, which means in your C# code, you'll access it via the Request.Form object. With what you're trying to do, you'd structure the jQuery URL as

它与您构建请求的方式有关。您的 JQuery 调用将数据作为 POST 数据发送到 User 控制器上的 AddLink 操作,这意味着在您的 C# 代码中,您将通过 Request.Form 对象访问它。根据您的尝试,您可以将 jQuery URL 构建为

/User/AddLink/{Title}/{URL}

This would require you to write a rule in your Global.ASAX file that handled that sort of input. In short, if you just modify your AddLink method as follows:

这将要求您在处理此类输入的 Global.ASAX 文件中编写规则。简而言之,如果您只是按如下方式修改您的 AddLink 方法:

public ActionResult AddLink()
{
    return Json(new { Result = string.Format(Request.Form["title"] + " " + Request.Form["url"])});
}

I believe you'll get the response you're looking for.

我相信你会得到你想要的回应。

回答by Kevin Pang

Have you tried writing out the full URL? I had a project running on my local IIS that had the same problem. The full url was http://localhost/myproject/user/addlink, but using "/user/addlink" in the jQuery ajax call was submitting to http://localhost/user/addlink(notice that "myproject" is missing because it's not actually the base url as far as jQuery knows).

你试过写出完整的 URL 吗?我有一个在本地 IIS 上运行的项目,它有同样的问题。完整的 url 是http://localhost/myproject/user/addlink,但在 jQuery ajax 调用中使用“/user/addlink”提交到http://localhost/user/addlink(注意“myproject”丢失是因为据 jQuery 所知,它实际上并不是基本 url)。

回答by buildmaster

have you tried using the jQuery.post method should be something like

你有没有试过使用 jQuery.post 方法应该是这样的

jQuery.post("/User/AddLink",AjaxLink,function(data,textStatus)
{
  if(textStatus=="success")
  {
    //do something with data which is the result from the call}
  }
  else
  {
  //failed somewhere along the line
  }
},"json");

post values are mapped to parameters in the MVC call so foxxtrot's code should be unnecessary.

post 值映射到 MVC 调用中的参数,因此应该不需要 Foxxtrot 的代码。

回答by buildmaster

Use a tool such as firebug to make sure that the url you expect is being called.

使用诸如 firebug 之类的工具来确保正在调用您期望的 url。

Debugging routine =>

调试例程 =>

  1. Use Firbug to determine that the correct url is being called and the correct data is being sent in the post
  2. Break the call in the action and make sure the parameters are being populated correctly
  3. Use Firebug again to check the response
  1. 使用 Firbug 确定正在调用正确的 url 并在 post 中发送正确的数据
  2. 中断操作中的调用并确保正确填充参数
  3. 再次使用 Firebug 检查响应

IE developer Toolbar can also be used instead of Firebug if you prefer IE. if the call url and post data seem correct, and the action isn't being called you should check your routing rules. ie does it have any default values in which case the MVC framework will be looking for a method signature that contains those default values (do you have {id} in your url rule?)

如果您更喜欢 IE,也可以使用 IE 开发人员工具栏代替 Firebug。如果调用 url 和 post 数据看起来正确,并且没有调用操作,则应检查路由规则。即它是否有任何默认值,在这种情况下,MVC 框架将寻找包含这些默认值的方法签名(您的 url 规则中有 {id} 吗?)

回答by Joseph White

I haven't taken the time to test it yet but it looks like it should work, the one think I would make sure is that you decorate the controller function to let it know it is looking for a post like the following:

我还没有花时间对其进行测试,但看起来它应该可以工作,我认为我会确保您装饰控制器功能以让它知道它正在寻找如下所示的帖子:

[HttpPost]
public ActionResult AddLink()
{
    return Json(new { Result = string.Format(Request.Form["title"] + " " +     Request.Form["url"])});
}

I should have time to test it this afternoon if none of these solutions work for you.

如果这些解决方案都不适合您,我今天下午应该有时间对其进行测试。

回答by Hyman1987

Ok, try this code using Ajax to pass data to your action method:

好的,尝试使用 Ajax 将数据传递给您的操作方法的这段代码:

jQuery.ajax({
            url: '@Url.Action("AddLink", "User")',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({ title: title, url: url }),
            success: function (result) { }
        });

回答by Jason Cidras

So I was having a little bit of a time trying to figure out how to get data back from an AJAX call. I was passing an JSON object from the view to the controller, and then return the ID of the object when it's done.

所以我花了一点时间试图弄清楚如何从 AJAX 调用中取回数据。我将一个 JSON 对象从视图传递到控制器,然后在完成后返回对象的 ID。

So, I finally got that working, and here's what I did on the view:

所以,我终于开始工作了,这是我在视图中所做的:

var obj = {
   property1 : '',
   property2 : ''
};

$.ajax({
    // Returns the full url
    url: '@Url.Action("Method", "Controller")', 
    // Sends as a json object, I actually have an object that maps to my ViewModel, this is just for explaining
    data: obj, 
    // You are telling that you are receiving a json object
    dataType: 'json', 
    success: function (id) {
       // do code here with id
    }
})

For my controller, I returned a Json object and did an AllowGet as a JsonRequestBehavior

对于我的控制器,我返回了一个 Json 对象并将 AllowGet 作为 JsonRequestBehavior

public ActionResult Method (ViewModel vm)
{
    int id = ... (do something with the vm)
    return Json(id, JsonRequestBehavior.AllowGet);
}

Edit: In addition, it appears you have POST as the type of request to the controller, and your controller method doesn't have the [HttpPost]annotation. That could also be the case.

编辑:此外,您似乎将 POST 作为对控制器的请求类型,并且您的控制器方法没有[HttpPost]注释。情况也可能如此。

I hope this helps!
Cheers!

我希望这有帮助!
干杯!