简体   繁体   中英

Ajax XMLHttpRequest to MVC 5 HttpPost ActionResult without jquery

Struggling to pass data object from javascript to C# MVC 5 .
I don't want to use jquery.
I can return DataInterface to Javascript but cannot send it to the server.
Using Visual Studio DEBUG I get DataInterface2.Age=0 and DataInterface2.Name=null.

Send from 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);

Receiving in 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);
    }
}

Your problem is use public variable, you need change to property with getter/setter .

Change from

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

to

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

I tested in local machine, it worked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM