如何从具有复杂键的 FormCollection 构建 C# 对象

发布于 2024-09-02 02:59:40 字数 738 浏览 2 评论 0原文

我有一个 javascript 对象 obj,它通过 $.post() 传递给 mvc 操作,如下所示:

var obj = {
    Items: [{ Text: "", Value: { Property1: "", Property2: "" },
            { Text: "", Value: { Property1: "", Property2: "" }]
};
$.post('MyAction', obj, function() {});

操作签名如下所示:

public ActionResult MyAction(FormCollection collection)
{
}

我需要能够从FormCollection,但是我遇到了一个问题,其中键位于表单中:

"Items[0][Text]"
"Items[0][Value][Property1]"
"Items[0][Value][Property2]"
"Items[1][Text]"
"Items[1][Value][Property1]"
"Items[1][Value][Property2]"

我想知道是否有一种干净的方法可以从给定的 FormCollection 构建所需的 C# 对象>。我知道我可以更改操作方法签名以接受我感兴趣的对象类型,但这提出了自己的问题。

i have a javascript object, obj, that gets passed to an mvc action via a $.post() like so:

var obj = {
    Items: [{ Text: "", Value: { Property1: "", Property2: "" },
            { Text: "", Value: { Property1: "", Property2: "" }]
};
$.post('MyAction', obj, function() {});

the action signature looks like this:

public ActionResult MyAction(FormCollection collection)
{
}

i need to be able to build an object from the FormCollection, however i'm running into an issue where the keys are in the form:

"Items[0][Text]"
"Items[0][Value][Property1]"
"Items[0][Value][Property2]"
"Items[1][Text]"
"Items[1][Value][Property1]"
"Items[1][Value][Property2]"

i'm wondering if there's a clean way to build the desired C# object from the given FormCollection. i understand that i could change the action method signature to take in the type of object i'm interested in, but that was presenting its own issues.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

最好是你 2024-09-09 02:59:40

如果您可以更改 javascript 端,以便发送 json 版本的数据,我认为您可以接受一个字符串并自己在控制器中进行 json 反序列化,或者使用模型绑定器来为您完成此操作。

If you can change the javascript side so you're sending in a json version of the data instead, I would think you could either accept a string and do a json deserialization yourself in the controller or do a model binder to do it for you.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文