asp.net-mvc MVC4 RC WebApi 参数绑定
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10955629/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MVC4 RC WebApi parameter binding
提问by Thad
I upgraded from MVC4 beta to RC and the latest autofac. The following action was binding properly, but now both parameters are null. I see they changed things about the Formatters and such but I am not sure what caused my problem
我从 MVC4 beta 升级到 RC 和最新的 autofac。以下操作已正确绑定,但现在两个参数都为空。我看到他们改变了格式化程序等,但我不确定是什么导致了我的问题
[HttpPost]
RedirectModel MyAction(string value1, string value1)
REQUEST
要求
Method: POST
Accept: application/json
URL: api/controller/myaction
BODY: {"value1":"1000", "value2":"foo"}
采纳答案by Jim Harte
Not really sure why the change from Beta, but I was able to make it work by changing the action signature to:
不确定为什么从 Beta 更改,但我能够通过将动作签名更改为:
[HttpPost]
RedirectModel MyAction(MyActionDTO dto)
and defining MyActionDTO as
并将 MyActionDTO 定义为
public class MyActionDTO
{
public string value1 { get; set; }
public string value2 { get; set; }
}
It was throwing an exception about not being able to bind to multiple body parameters using the two string paramaters. I guess using the DTO object more closely represents what you're sending in the AJAX call (a JSON object).
它抛出了一个关于无法使用两个字符串参数绑定到多个主体参数的异常。我想使用 DTO 对象更接近地代表您在 AJAX 调用(一个 JSON 对象)中发送的内容。
回答by mhu
When you want to avoid using a DTO object, try this:
当你想避免使用 DTO 对象时,试试这个:
[HttpPost]
RedirectModel MyAction(dynamic value1, dynamic value2) {
string sValue1 = value1;
string sValue2 = value2;

