简体   繁体   中英

How to pass array in a JSON object from javascript to asp.net mvc controller method?

My model:

public class Company
{
    [BsonElement]
    [BsonRepresentation(MongoDB.Bson.BsonType.String)]
    public String PlaceId { get; set; }

    [BsonElement]
    [BsonRepresentation(MongoDB.Bson.BsonType.String)]
    public string Name { get; set; }

    [BsonElement]
    [BsonRepresentation(MongoDB.Bson.BsonType.String)]
    [BsonIgnoreIfNull]
    public string Email { get; set; }

    [BsonElement]
    [BsonRepresentation(MongoDB.Bson.BsonType.Double)]
    public Double Rating { get; set; }

    [BsonElement]
    [BsonIgnoreIfNull]
    public Department Department { get; set; }

    [BsonElement]
    [BsonIgnoreIfNull]
    public Product Product { get; set; }

    [BsonElement]        
    public Comment[] Comments { get; set; }       
}

public class Comment
{
    [BsonElement]
    public String Text { get; set; }
}

My controller method:

public JsonResult SavePlace(Company company)
{
    if (company != null)
    {
        var client = new MongoClient("mongodb://localhost");
        var database = client.GetDatabase("mongogoogleplace");
        var placeData = database.GetCollection<BsonDocument>("googledatanew");


        var department = company.Department.ToBsonDocument();
        var product = company.Product.ToBsonDocument();
        //var comments = company.Comments.ToBsonElement();

        var companyModel = company.ToBsonDocument();           

        var filter = Builders<BsonDocument>.Filter.Eq("PlaceId", company.PlaceId);
        var projection = Builders<BsonDocument>.Projection
                .Exclude("_id");
        //BsonDocument document = new BsonDocument();

        var document = placeData.Find(filter).Project(projection).FirstOrDefault();
        var documentJson = document.ToJson();

        return Json(documentJson);   
    }
    else
    {
        return Json(new { data = "error." });
    }
}

Javascript snippet:

var company = { "PlaceId": PlaceId, "Name": Name, "Rating": Rating, "Comments": [{ Comment: { Text: '' } }, { Comment: { Text: '' } }, { Comment: { Text: '' } }, { Comment: { Text: '' } }, { Comment: { Text: '' } } ] };

for (var i = 0; i < CommentsArray.length; i++) {
    company.Comments[i].Comment.Text = CommentsArray[i];
};

$.ajax({
    type: "POST",
    url: "../Home/SavePlace",
    data:  company,
    // dataType: "json",

    success: function (data){}

But every time I get the comments to be null.

Change:

data:  company

To

data : {company: company}

The Action expects an object with a parameter named company.

In your data you need to convert object to JSON in this way:

data: JSON.stringify(company)

Now in your method you should be able to get the comments. Another way is this:

data: { company: company }

Where the first name must be the same as your parameter name in the action method. I'm not sure at 100% that works because I'm not sure that company will be converted to a C# object correctly.

Your Action must look like this:

[HttpPost]
public JsonResult SavePlace(Company company)
{
    // Your code
}

Your Ajax request:

$.ajax({
    type: "POST",
    url: "../Home/SavePlace",
    data:  JSON.stringify(company),
    contentType: "application/json; charset=utf-8",
    success: function (data){}
});

Define your company object like this:

var company = {
    PlaceId: "XXXX", 
    Name: "XXXX", 
    Rating: 10.0, 
    Comments: [
        Comment: { Text: '' },
        Comment: { Text: '' },
        Comment: { Text: '' },
        Comment: { Text: '' },
        Comment: { Text: '' }
    ]
};

Here is a complete working example. The code of the view:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
    var company = {
        PlaceId: "XXXX", 
        Name: "XXXX", 
        Rating: 10.0, 
        Comments: [
            Comment: { Text: '' },
            Comment: { Text: '' },
            Comment: { Text: '' },
            Comment: { Text: '' },
            Comment: { Text: '' }
        ]
    };

    $(document).ready(function(){
        $("#toto").on("click", function () {
            $.ajax({
                type: "POST",
                url: "../Home/SavePlace",
                data:  JSON.stringify(company),
                contentType : "application/json; charset=utf-8",
                dataType: "json",
            });
        });
    });

</script>
<input type="button" id="toto" />

The c# and controller code:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return this.View();

    }

    [HttpPost]
    public JsonResult SavePlace(Company company)
    {
        if (company != null)
        {

            return Json(new { data = "fine." });
        }
        else
        {
            return Json(new { data = "error." });
        }
    }
}

public class Company
{
    public String PlaceId { get; set; }

    public string Name { get; set; }

    public string Email { get; set; }

    public Double Rating { get; set; }

    public object Department { get; set; }

    public object Product { get; set; }

    public Comment[] Comments { get; set; }
}

public class Comment
{
    public String Text { get; set; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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