要通过全JSON对象为MVC控制器 [英] To pass whole JSON objects into controller of MVC
本文介绍了要通过全JSON对象为MVC控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想整个JSON对象传递到MVC中的控制器,这样我可以访问整个对象。
我使用以下code ..
I wants to pass whole JSON objects into controller in MVC so that i can access whole object. I am using following code ..
称为视图脚本
var Email = {
To: $("#txtTo").val(),
Text: $("#txtTest").val(),
Subject: $("#txtSubject").val()
};
$.ajax({
type: "POST",
url: ("Controller/SendEmail"),
data: JSON.stringify(Email ),
datatype: "json",
contentType: "application/json; charset=utf-8",
cache: false,
success: function(htmlResult) {
alert("Mail Send")
},
error: function(msg) { alert("Error Occurs."); }
});
但是当我把这个控制器中:
but when i call this in controller :
public ActionResult SendEmail(Model model)
{
string to = model.To ;
}
它给了空。如何解决此问题?
it gives null. How to resolve this?
推荐答案
您必须做出这样一个类:
You have to make a class like this :
public class ObjectFilter : ActionFilterAttribute
{
public string Param { get; set; }
public Type RootType { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if ((filterContext.HttpContext.Request.ContentType ?? string.Empty).Contains("application/json"))
{
object o = new System.Runtime.Serialization.Json.DataContractJsonSerializer(RootType).ReadObject(filterContext.HttpContext.Request.InputStream);
filterContext.ActionParameters[Param] = o;
}
}
}
你,你要传递到JSON类是如下:
you Class that you wants to pass into JSON is as follow :
public class Email
{
public To{ get; set; }
public string Subject { get; set; }
public string Text { get; set; }
}
现在不得不调用这个类的属性,在你的控制器:
Now to have to call this class as attributes in your controller as :
[ObjectFilter(Param = "model", RootType = typeof(Email))]
public ActionResult SendEmail(Email model)
{
string to = model.To ;
}
这会给你想要的结果。
这篇关于要通过全JSON对象为MVC控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文