将数据发送到使用JSON

将数据发送到使用JSON

本文介绍了将数据发送到使用JSON MVC控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用JQuery Ajax来作出一个ASP.NET MVC控制器的简单调用。这是我的code

I am using JQuery Ajax to make a simple call to an ASP.NET MVC controller. Here is my code

   function postdata(idno) {
   console.log(idno);

   $.ajax({
        type: 'POST',
        url: "/IM/GetMessages",
        contentType: 'application/json',
        dataType: 'json',
        data: JSON.stringify({ 'fUserId': idno }),
        success: function (data) { /*CODE*/

    });}

控制器看起来像这样

The controller looks like this

     [HttpPost]
     public ActionResult GetMessages(decimal? fUserId)
     {
        var list = WebUtility.IMMessages.Where(p =>
            (p.ToUserId == Session.UserId  && (!fUserId.HasValue || fUserId.HasValue && p.User == fUserId.Value)))
            .OrderBy(p => p.CreatedDateTime)
            .Select(p => new { MessageId = p.RecordId, MessageBody = p.Description1 });

        return Json(list, JsonRequestBehavior.AllowGet);
     }

问题是我的数据不会传递给我的控制器,空通行证代替。我该如何解决这个问题呢?我看IDNO在控制台上,一切似乎确定。

The problem is that my data doesn't pass to my controller, "null" passes instead. how can I correct this issue? I am watching "idno" on console and everything seems to be OK.

推荐答案

没有理由,如果你问我一个参数转换成JSON。而不是仅仅做到这一点:

There is no reason to convert a single parameter into a JSON if you ask me. Instead just do this:

$.ajax({
    type: 'POST',
    url: "/IM/GetMessages?fUserId=" + idno,
    dataType: 'json',
    success: function (data) { /*CODE*/
});

这样你仍然可以拿回JSON,但你传递一个参数值。现在,如果你真的需要发送的对象我看不出什么问题,你的code。您可能要声明一个JavaScript变量,并把它变成这样一个JSON对象:

This way you can still get back JSON but you pass single parameter value. Now if you really need to send an object I don't see anything wrong with your code. You might want to declare a javascript variable and turn it into a json object like this:

var myVar = { fUserId: idno };

,然后用它在你的Ajax请求:

and then use that in your ajax request:

$.ajax({
    type: 'POST',
    url: "/IM/GetMessages",
    contentType: 'application/json',
    dataType: 'json',
    data: JSON.stringify(myVar),
    success: function (data) { /*CODE*/

});

我这样做,每天和它工作正常,我既可空和非可空类型...

I do this daily and it works fine for me with both nullable and non-nullable types...

这篇关于将数据发送到使用JSON MVC控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 03:18