【问题标题】:orchardcms/mvc null values when postingorchardcms/mvc 发布时的空值
【发布时间】:2013-02-06 18:11:56
【问题描述】:
public class Address
    {
        public string Street { get; set;}
    }


public class MyModel
    {
        public string Name { get; set;}
        public Address MyAddress { get; set;}
    }


public class MyController : Controller
{
        [HttpPost]
        public JsonResult DoStuff(MyModel model)
        {
            // model.Name has its value
            // model.MyAddress is there, but its .Street is always null
            // Do stuff
        }
}

这就是我发布到控制器的方式

var data =
    {
        __RequestVerificationToken: $("input[name=__RequestVerificationToken]").val(),
        Name: "Arnold",
        MyAddress: 
        {
               Street: "my address"
        }
    }

$.ajax({
        type: 'POST',
        url: "/myroute/dostuff", //Yes i should not use the hardcoded url but this is just for show
        data: data,
        async: false,
        success: function (result) {
            // ...
        },
        dataType: 'json',
    });

看着提琴手发布正确的数据.. 如果我查看 ModelState,它只有一个键,“名称”。

编辑:

如果我这样做:

public class MyController : Controller
{
        [HttpPost]
        public JsonResult DoStuff(FormCollection formCollection)
        {
            // formCollection has all the data..
            // so i guess its the binding? :o any ideas how to fix?
            // Do stuff
        }
}

【问题讨论】:

  • 我认为这不应该被标记为 OrchardCms:它似乎纯粹是一个 ASP.NET MVC 模型绑定问题。问题中还缺少:帖子的结构。模型绑定很大程度上依赖于发布数据结构的约定。

标签: asp.net-mvc


【解决方案1】:

如果在操作方法的第一行调用UpdateModel(model) 会发生什么?这可能是因为模型绑定没有隐式获取 Address 属性,您需要给它一个显式的微调。

【讨论】:

  • 如果我做 UpdateModel(model) 我得到一个 System.Reflection.TargetInvocationException “异常已被调用的目标抛出。”,InnerException:“集合是只读的”。
  • 这很奇怪。您的 MyModel 对象没有任何集合属性。堆栈跟踪中还有什么有用的吗?
  • 啊,是的,你说得对,我看错了一段代码:P 但是,执行 UpdateModel(model) 似乎没有什么不同。
  • UpdateModel(model.MyAddress) 怎么样?
  • FormCollection 中传递了什么?它可能与在回发表单之前如何命名表单元素有关。模型绑定仅在表单具有正确命名的要绑定的元素时才有效。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-13
相关资源
最近更新 更多