Michael
Michael

Reputation: 13616

Why I get error when I try to return anonymous type to client?

In my action Method I try to return anonymous type:

public JsonResult GetAssociatedProperty(int id)
{
    try
    {
        var property = _repository.GetLayerProperty(id);

        return Json(new { Result = "OK",  new { property.Id, property.VectorLayerId, property.FieldName, property.FieldType, property.FieldValue, property.Required} }, JsonRequestBehavior.AllowGet);
    }
    catch (Exception ex)
    {

        throw;
    }
}

but I get this error:

Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.

On this row:

return Json(new { Result = "OK",  new { property.Id, property.VectorLayerId, property.FieldName, property.FieldType, property.FieldValue, property.Required} }, JsonRequestBehavior.AllowGet);

Any idea how can I fix the error and send anonymous type to the client?

Upvotes: 0

Views: 123

Answers (2)

René Vogt
René Vogt

Reputation: 43876

As the error message tells you, you need a name for the second member of your anonymous type:

 return Json(new { 
                Result = "OK",  
                Prop = new { property.Id, property.VectorLayerId, property.FieldName, property.FieldType, property.FieldValue, property.Required} },
             JsonRequestBehavior.AllowGet);

Upvotes: 3

Shahzad Khan
Shahzad Khan

Reputation: 530

public JsonResult GetAssociatedProperty(int id)
        {
            try
            {
                var property = _repository.GetLayerProperty(id);

                return Json(new {
                    Result = "OK",
                    Id = property.Id,
                    VectorLayerId = property.VectorLayerId,
                    FieldName = property.FieldName,
                    FieldType = property.FieldType,
                    FieldValue = property.FieldValue,
                    Required = property.Required 
                }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {

                throw;
            }
        }

Above code might be help you.

Upvotes: -2

Related Questions