我正在使用ASP.NET Core,现在尝试使用post与jQuery。 我遇到的情况是这样的:
我有一个模特
public class Model { int INT_VALUE { get; set; } string STR_VALUE { get; set; } int SOME { get; set; } }和API一样
[HttpPost] public Model GetValues(string val) { Model m = new Model { INT_VALUE = 1, STR_VALUE = "hi", SOME = "there" }; return m; }现在我使用jQuery请求post
$.post('api/GetValues', { val: "abc" }) .done(function (data) { console.log(data) if (data.INT_VALUE === 1) { console.log("Hit!"); } });关键是如果我得到INT_VALUE的模型=== 1 log'Hit !' 但它不起作用。 (没有进入console.log("Hit!") )
所以,我检查接收的json值,然后我发现了拼写错误的奇怪值
{"inT_VALUE":1,"stR_VALUE":"hi","some":"there"}我的期望是什么
{"INT_VALUE":1,"STR_VALUE":"hi","SOME":"there"}要么
{"int_value":1,"str_value":"hi","some":"there"}有没有办法改变我能期待的拼写?
I'm using ASP.NET Core and now trying to use post with jQuery. The situation I encounter was like this:
I have a model
public class Model { int INT_VALUE { get; set; } string STR_VALUE { get; set; } int SOME { get; set; } }and an API like
[HttpPost] public Model GetValues(string val) { Model m = new Model { INT_VALUE = 1, STR_VALUE = "hi", SOME = "there" }; return m; }Now I request with post using jQuery
$.post('api/GetValues', { val: "abc" }) .done(function (data) { console.log(data) if (data.INT_VALUE === 1) { console.log("Hit!"); } });The point is that if I get Model with INT_VALUE === 1 log 'Hit!' but it did not work. (did not get in console.log("Hit!"))
So, I check the receiving json value then I found strange values with wrong spelling like
{"inT_VALUE":1,"stR_VALUE":"hi","some":"there"}What I expected is
{"INT_VALUE":1,"STR_VALUE":"hi","SOME":"there"}or
{"int_value":1,"str_value":"hi","some":"there"}Is there any way to change spelling which I can expect?
最满意答案
我认为您可以更改为使用PascalCase来获取模型的属性(例如:IntValue,StrValue ...)。 然后你可以通过以下设置强制Json Serializer使用PascalCase。
在Startup.cs文件中,找到您的ConfigureServices方法并像这样更新它
public void ConfigureServices(IServiceCollection services) { services.AddMvc() .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver()); }然后在客户端,您可以使用模型中定义的相同名称访问属性(IntValue,StrValue ...)。
I think you could change to use PascalCase for properties of your model (ex: IntValue, StrValue...). Then you could force Json Serializer to use PascalCase by following setting.
In your Startup.cs file, find your ConfigureServices method and update it like this
public void ConfigureServices(IServiceCollection services) { services.AddMvc() .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver()); }Then in client side, you could access property using the same name as defined in your model (IntValue, StrValue...).
更多推荐
发布评论