简体   繁体   English

将对象从Javascript绑定到ASP.NET MVC2 Controller中的模型

[英]binding a list of objects from Javascript to model in ASP.NET MVC2 Controller

I have the following JSON that was obtained after calling JSON.stringify from my javascript 我有从我的JavaScript调用JSON.stringify之后获得的以下JSON

{"parameters":"[{\"ParamName\":\"@s\",\"ParamValue\":\"12\"},{\"ParamName\":\"@t\",\"ParamValue\":\"21\"}]"}

How do i map this to the following model in my ASP.Net MVC2 controller 如何将其映射到ASP.Net MVC2控制器中的以下模型

public class SCVM
{
    public string content { get; set; }
    public string type { get; set; }
    public List<Parameters> parameters { get; set; }

    public SCVM()
    {
        parameters = new List<Parameters>();
    }
}

public class Parameters
{
    public string ParamName { get; set; }
    public string ParamValue { get; set; }
}

I am trying to get this in either a dictionary format or a list objects, but finding difficult to work it out the right way. 我试图以字典格式或列表对象的形式获取此文件,但发现很难以正确的方式进行处理。

If your json would look like this: it probably should. 如果您的json看起来像这样:可能应该这样。 (see my comment on your question) (请参阅我对您问题的评论)

{
    "parameters":[
        {
            "ParamName":"@s",
            "ParamValue":"12"
        },
        {
            "ParamName":"@t",
            "ParamValue":"21"
        }
    ]
}

with this piece of javascript you'll create the correct json: 使用这段JavaScript,您将创建正确的json:

var parametersCollection = {
    parameters: []
}; 

function QueryParameters(paramName, paramValue) { this.ParamName = paramName;     this.ParamValue = paramValue; }

parametersCollection.parameters.push(new QueryParameters("@s", "12"));
parametersCollection.parameters.push(new QueryParameters("@t", "21"));

var json = JSON.stringify(parametersCollection);

you could deserialize is with Json.NET see here like so: 你可以反序列化与Json.NET 看到这里 ,像这样:

SCVM scvm = JsonConvert.DeserializeObject<SCVM>(json);

where json is a string with the json formatted like I showed 其中json是一个字符串,其json格式如我所示

Here is an excellent tutorial on how to post json data to an MVC2 site using jquery. 是有关如何使用jquery将json数据发布到MVC2站点的出色教程。 You wouldn't even have to use the Json.NET lib to deserialize your json. 您甚至不必使用Json.NET库反序列化json。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM