没有jquery的Ajax XMLHttpRequest到MVC 5 HttpPost ActionResult

时间:2015-04-20 04:56:10

标签: c# ajax asp.net-mvc-5 xmlhttprequest

努力将数据对象从javascript传递到C# MVC 5 我不想使用jquery 我可以将DataInterface返回给Javascript,但无法将其发送到服务器 使用Visual Studio DEBUG我得到DataInterface2.Age=0DataInterface2.Name=null.

Javascipt发送: -

var uri = '/Action/ActionInterface'
var xmlhttp;
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
        fDone(JSON.parse(xmlhttp.responseText));
    }
}
var data = { "Name": "Joe", "Age": 33  };
var sendstr = JSON.stringify(data);
xmlhttp.open("POST", uri, true);
xmlhttp.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
xmlhttp.send(sendstr);

接收 C#: -

public class DataInterface
{
    public string Name;
    public Int16 Age;
    //public DateTime Birthdate;
}
public class ActionController : Controller
{
    [HttpPost]
    public ActionResult ActionInterface(DataInterface DataInterface2)
    {
        .... Using Debug DataInterface2.Age=0 and DataInterface2.Name=null 
        ....
        return Json(DataInterface1, JsonRequestBehavior.DenyGet);
    }
}

1 个答案:

答案 0 :(得分:1)

您的问题是使用public变量,您需要将property更改为getter/setter

更改自

public class DataInterface
{
    public string Name;
    public Int16 Age;
}

public class DataInterface
{
    public string Name { get; set; }
    public int Age { get; set; }
}

我在本地计算机上测试过,它起作用了。