[英]How to send a JSON data object to the server using Javascript XMLHttpRequest?
[英]How to send Json object (or string data) from Javascript xmlhttprequest to MVC Controller
我在ASP.NET MVC中创建了一个Web应用程序,并尝试通过Javascript AJAX调用控制器。 在Jquery中,我们可以发送一个json对象,MVC Model Binder会自动尝试创建一个.NET对象并将控制器作为参数传入。
但是我使用的是不能使用jquery的web worker。 所以我通过vanilla xmlhttprequest对象进行AJAX调用。 有没有办法通过这种方法发送Json对象?
我使用了xmlhttprequest的send方法,但模型对象在控制器中显示为null :(
您应该只能使用JSON2对其进行字符串化,并在执行发布时将Content-Type
标头设置为application/json
。
http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js
你会做的事情如下:
var xhr = new XMLHttpRequest();
xhr.open('POST', '/Controller/Action');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
xhr.send(JSON.stringify(myData));
这是一个例子。 它假定您使用的是具有内置JsonValueProviderFactory
ASP.NET MVC 3.0。 如果这不是你的情况,你可以看一下这篇博客文章 。
查看型号:
public class MyViewModel
{
public string Prop1 { get; set; }
public string Prop2 { get; set; }
}
控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult SomeAction(MyViewModel model)
{
return Content("success", "text/plain");
}
}
视图:
<script type="text/javascript">
var http = new XMLHttpRequest();
var value = '{ "prop1": "value 1", "prop2": "value 2" }';
// It would be better to use JSON.stringify to properly generate
// a JSON string
/**
var value = JSON.stringify({
prop1: 'value 1',
prop2: 'value 2'
});
**/
http.open('POST', '/Home/SomeAction', true);
http.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
http.setRequestHeader('Content-Length', value.length);
http.onreadystatechange = function () {
if (http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(value);
</script>
使用$ .Ajax(),您可以轻松地将数据从javascript传输到MVC中的Controller。
以供参考,
var uname = 'Nikhil Prajapati';
$.ajax({
url: "/Main/getRequestID", // This is path of your Controller with Action Result. dataType: "json", // Data Type for sending the data data: { // Data that will be passed to Controller 'my_name': uname, // assign data like key-value pair // 'my_name' like fields in quote is same with parameter in action Result }, type: "POST", // Type of Request contentType: "application/json; charset=utf-8", //Optional to specify Content Type. success: function (data) { // This function is executed when this request is succeed. alert(data); }, error: function (data) { alert("Error"); // This function is executed when error occurred. }
)};
而且,现在在控制器端,
public ActionResult getRequestID(String my_name){
MYDBModel myTable = new Models.MYDBModel(); myTable.FBUserName = my_name; db.MYDBModel.Add(myTable); db.SaveChanges(); // db object of our DbContext.cs //return RedirectToAction(“Index”); // After that you can redirect to some pages… return Json(true, JsonRequestBehavior.AllowGet); // Or you can get that data back after inserting into database.. This json displays all the details to our view as well. }
有关更多参考..请访问.. 将数据从Java脚本发送到MVC中的Controller
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.