Asp.net mvc 带有特殊字符的.net mvc 4模型绑定
如何为json对象创建模型类,如:Asp.net mvc 带有特殊字符的.net mvc 4模型绑定,asp.net-mvc,Asp.net Mvc,如何为json对象创建模型类,如: { "model" : { "@foo": "bar", "#baz": "fu" }} 如果我想将变量名中带有特殊字符@和#的json模型传递给我的控制器,那么如何编写模型或声明类变量: $http.post('@Url.Action("myController","test")', model, { headers: { 'Content-Type': 'application/json; charset=utf-8' } }) public cl
{ "model" : { "@foo": "bar", "#baz": "fu" }}
如果我想将变量名中带有特殊字符@
和#
的json模型传递给我的控制器,那么如何编写模型或声明类变量:
$http.post('@Url.Action("myController","test")', model, { headers: { 'Content-Type': 'application/json; charset=utf-8' } })
public class MyModel
{
// public string @foo { get; set; }
// public #bar { get; set; }
}
public ActionResult myController(MyModel model) {
return View();
}
有两个简单的解决方案
迭代json对象并更改变量名
将json作为stringjson.stringify(data)
发布,并自行序列化
如下所述:
public ActionResult myController(string model)
{
var ser = new System.Web.Script.Serialization.JavascriptSerializer();
Dictionary<string, string> dictionary = ser.Deserialize<Dictionary<string, string>>(model);
// Do something with the dictionary
}
public ActionResult myController(字符串模型)
{
var ser=new System.Web.Script.Serialization.JavascriptSerializer();
Dictionary Dictionary=ser.反序列化(model);
//用字典做点什么
}
如果使用Json.NET,则可以使用[JsonProperty]
属性装饰属性名称:
[JsonProperty(PropertyName = "@foor")]
public string Foo { get; set; }
[JsonProperty(PropertyName = "#bar")]
public Bar { get; set; }
你好我接受了你的回答,只是在等待其他建议。但是你的很完美,谢谢。