- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我有一个接受列表作为参数的 ActionResult 方法:
[HttpPost]
public ActionResult MyMethod (List<ClassA> json)
{
...
}
这会将传入的 json 字符串绑定(bind)到已填充的 ClassA 对象的通用列表中。
问题是有时传入的 json 只是一个 json 对象,而不是一个 json 对象数组。
有什么方法可以抢占它,以便我可以直接绑定(bind)到 ClassA 和 List?或者我可以使用其他一些技术吗?
以下是 JSON 的发送方式(作为数组):
var myjsonarray = [{
"ID": "1",
"FirstName": "John",
"LastName": "Doe",
}, {
"ID": "2",
"FirstName": "Jane",
"LastName": "Doe",
}];
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Home/MyPage",
data: JSON.stringify(myjsonarray),
dataType: 'json'
});
以上过程没问题。这也有效:
var myjsonarray = [{
"ID": "1",
"FirstName": "John",
"LastName": "Doe",
}];
但是当我作为一个未包装在数组中的单个对象发送时:
var myjsonarray = {
"ID": "1",
"FirstName": "John",
"LastName": "Doe",
};
我的 ActionResult 方法参数为空:
json == null
最佳答案
虽然您的问题并不清楚,但从其他答案的评论来看,您似乎无法控制向您发送此 JSON 的客户端代码。 (如果你这样做了,最简单的解决方案是在发送之前将你的单个对象包装在一个数组中,正如其他人已经建议的那样。)
如果 MVC 允许我们在 Controller 中添加方法重载来处理这种情况,那就太好了,例如:
[HttpPost]
public ActionResult MyMethod (List<ClassA> list)
{
...
}
[HttpPost]
public ActionResult MyMethod (ClassA single)
{
...
}
虽然这可以很好地编译,但不幸的是,当您在运行时点击该方法时,它会导致 System.Reflection.AmbiguousMatchException
。
因此,看起来您需要创建自定义 IModelBinder解决问题。虽然我之前没有实现过自定义模型绑定(bind)器,但我将其视为挑战并提出了以下建议。您显然必须根据自己的需要对其进行调整,但它似乎适用于您的示例。
代码如下:
public class CustomModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
IValueProvider provider = bindingContext.ValueProvider;
// Check whether we have a list or a single object. If we have a list
// then all the properties will be prefixed with an index in square brackets.
if (provider.ContainsPrefix("[0]"))
{
// We have a list. Since that is what the controller method is
// expecting, just use the default model binder to do the work for us.
return ModelBinders.Binders.DefaultBinder.BindModel(controllerContext, bindingContext);
}
else
{
// We have a single object.
// Bind it manually and return it in a list.
ClassA a = new ClassA();
a.ID = GetValue<int>(provider, "ID");
a.FirstName = GetValue<string>(provider, "FirstName");
a.LastName = GetValue<string>(provider, "LastName");
return new List<ClassA> { a };
}
}
private T GetValue<T>(IValueProvider provider, string key)
{
ValueProviderResult result = provider.GetValue(key);
return (result != null ? (T)result.ConvertTo(typeof(T)) : default(T));
}
}
要将此自定义绑定(bind)器插入 MVC 管道,请将此行添加到 Global.asax.cs
中的 Application_Start()
方法。
ModelBinders.Binders.Add(typeof(List<ClassA>), new CustomModelBinder());
现在,显然这不是一个通用的解决方案;它是专门为处理 ClassA
而定制的。我必须相信,有可能制定一个通用解决方案来处理任何类型列表的这种“单一或列表”情况,但这要复杂得多,超出了这个答案的范围。为此,您可能还需要创建自定义 IModelBinderProvider
.如果你想达到那个水平,你需要自己调查。这是一个 MSDN article这可能会让您更深入地了解绑定(bind)在幕后的工作原理。
关于c# - 如何使用相同的 MVC Controller 方法处理数组或单个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18642879/
我的一位教授给了我们一些考试练习题,其中一个问题类似于下面(伪代码): a.setColor(blue); b.setColor(red); a = b; b.setColor(purple); b
我似乎经常使用这个测试 if( object && object !== "null" && object !== "undefined" ){ doSomething(); } 在对象上,我
C# Object/object 是值类型还是引用类型? 我检查过它们可以保留引用,但是这个引用不能用于更改对象。 using System; class MyClass { public s
我在通过 AJAX 发送 json 时遇到问题。 var data = [{"name": "Will", "surname": "Smith", "age": "40"},{"name": "Wil
当我尝试访问我的 View 中的对象 {{result}} 时(我从 Express js 服务器发送该对象),它只显示 [object][object]有谁知道如何获取 JSON 格式的值吗? 这是
我有不同类型的数据(可能是字符串、整数......)。这是一个简单的例子: public static void main(String[] args) { before("one"); }
嗨,我是 json 和 javascript 的新手。 我在这个网站找到了使用json数据作为表格的方法。 我很好奇为什么当我尝试使用 json 数据作为表时,我得到 [Object,Object]
已关闭。此问题需要 debugging details 。目前不接受答案。 编辑问题以包含 desired behavior, a specific problem or error, and the
我听别人说 null == object 比 object == null check 例如: void m1(Object obj ) { if(null == obj) // Is thi
Match 对象 提供了对正则表达式匹配的只读属性的访问。 说明 Match 对象只能通过 RegExp 对象的 Execute 方法来创建,该方法实际上返回了 Match 对象的集合。所有的
Class 对象 使用 Class 语句创建的对象。提供了对类的各种事件的访问。 说明 不允许显式地将一个变量声明为 Class 类型。在 VBScript 的上下文中,“类对象”一词指的是用
Folder 对象 提供对文件夹所有属性的访问。 说明 以下代码举例说明如何获得 Folder 对象并查看它的属性: Function ShowDateCreated(f
File 对象 提供对文件的所有属性的访问。 说明 以下代码举例说明如何获得一个 File 对象并查看它的属性: Function ShowDateCreated(fil
Drive 对象 提供对磁盘驱动器或网络共享的属性的访问。 说明 以下代码举例说明如何使用 Drive 对象访问驱动器的属性: Function ShowFreeSpac
FileSystemObject 对象 提供对计算机文件系统的访问。 说明 以下代码举例说明如何使用 FileSystemObject 对象返回一个 TextStream 对象,此对象可以被读
我是 javascript OOP 的新手,我认为这是一个相对基本的问题,但我无法通过搜索网络找到任何帮助。我是否遗漏了什么,或者我只是以错误的方式解决了这个问题? 这是我的示例代码: functio
我可以很容易地创造出很多不同的对象。例如像这样: var myObject = { myFunction: function () { return ""; } };
function Person(fname, lname) { this.fname = fname, this.lname = lname, this.getName = function()
任何人都可以向我解释为什么下面的代码给出 (object, Object) 吗? (console.log(dope) 给出了它应该的内容,但在 JSON.stringify 和 JSON.parse
我正在尝试完成散点图 exercise来自免费代码营。然而,我现在只自己学习了 d3 几个小时,在遵循 lynda.com 的教程后,我一直在尝试确定如何在工具提示中显示特定数据。 This code
我是一名优秀的程序员,十分优秀!