weixin_33725807 2018-08-07 17:52 采纳率: 0%
浏览 26

Ajax调用MVC控制器

I'm trying to pass some data with ajax call to a c# mvc controller. Even though the task should be straight forward, I am unable to get the mvc controller to read the data I'm passing through the ajax call....

I've implemented the following code within my MVC controller

[HttpPost]
public string tt(string o)
{            
    return o;
}

[HttpPost]
public string tt2(string o)
{
    return "lala";
}

And I'm triggering the following ajax calls from the browser

$.ajax({
    url: "/Home/tt2",
    type: "POST",
    contentType: "application/json;",
    data: JSON.stringify({ o: 'asdas'}),     
    success: function(e){console.log(e+'    correct');},
    error: function(e){console.log(e+'    incorrect');}
});

$.ajax({
    url: "/Home/tt",
    type: "POST",
    contentType: "application/json;",
    data: JSON.stringify({ o: 'asdas'}),     
    success: function(e){console.log(e+'    correct');},
    error: function(e){console.log(e+'    incorrect');}
});

As a result when running the first ajax call the result is

lala    correct

And for the second ajax call, the result is

undefined    correct

In the mean time these are some stuff I tried

  • Adding dataType: "json", to the ajax call
  • Changing the string data from {o: 'asdas'} to 'asdas'
  • Removing the JSON.stringify
  • Adding the charset=utf-8 to the contentType
  • Changing the ajax call type and MVC controller method from POST to GET to PUT
  • Changing the MVC controller method parameter from string to int
  • Removing the error method from the ajax call
  • Changing the data from data: {o: 'asdas'} to data: {"o":"asdas"}
  • Changing the data from data: {"o":"asdas"} to data: JSON.stringify({"o":"asdas"})

I know that simple string or int can be passed through the URL as query strings but it would be an issue when passing a list of objects..

Something aside is that the call is being done correctly to the URL because when I set a breakpoint within the called method, it does get triggered but the parameter always is null..

Any thoughts on how to make ajax call work?

  • 写回答

2条回答 默认 最新

  • weixin_33686714 2018-08-07 17:57
    关注

    Your request should be like this:

    $.ajax({
                url: '@Url.Action("tt", "Home")',
                data: {
                    "o": "asdasdas"
                },
                cache: false,
                type: "POST",
                success: function (response) {
    
                },
                error: function (xhr) {
                }
                });
    
    评论

报告相同问题?

悬赏问题

  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。